gpt4 book ai didi

php - laravel 如何在静态方法中使用 $this 上下文?

转载 作者:可可西里 更新时间:2023-11-01 13:39:46 26 4
gpt4 key购买 nike

Laravel 如何在“路由”目录中的 console.php 文件中使用 $this->comment() 方法,而 Artisan::command() 是一个静态方法?

enter image description here

<?php

use Illuminate\Foundation\Inspiring;

Artisan::command('inspire', function() {
$this->comment(Inspiring::(quote));
})->describe('Display an inspiring quote');

最佳答案

$this 并未在静态方法本身内部使用,而是在传递给该方法的闭包中使用。 From the Laravel manual :

The Closure is bound to the underlying command instance, so you have full access to all of the helper methods you would typically be able to access on a full command class.

所以 $this 在此上下文中是一个 Command 实例。这是使用 PHP 的 bindTo 实现的。方法,它允许您指定任何给定闭包的范围。


不过,这种方法并不是 Artisan 命令独有的。一般来说,我们称这个特征为Facades :

Facades provide a "static" interface to classes that are available in the application's service container. Laravel ships with many facades which provide access to almost all of Laravel's features. Laravel facades serve as "static proxies" to underlying classes in the service container, providing the benefit of a terse, expressive syntax while maintaining more testability and flexibility than traditional static methods.

还有很多其他外观,它们都提供对服务容器内实例的静态访问。一些更常见的外观和方法是:

  • Cache::get('key')Cache::set('key', 'value')
  • Request::input('some_field')Request::only('some_field')
  • Log::info('注意这个...')
  • ...

关于php - laravel 如何在静态方法中使用 $this 上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52610280/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com