Php 是否可以在Laravel facade的构造函数中初始化变量?
如果我正在创建一个自定义facade,并且希望在使用Php 是否可以在Laravel facade的构造函数中初始化变量?,php,laravel,laravel-5,Php,Laravel,Laravel 5,如果我正在创建一个自定义facade,并且希望在使用customFacade::doSomething()的每个实例上初始化某些变量,那么这可能吗?我这样做的主要目的是能够存储作为其他对象的变量,并直接对其调用函数。示例为customFacade::client->send(),在本例中,client是具有send()函数的对象的初始化变量。我知道我可以使用一个函数client(),然后返回对象的一个新实例,这样send()就可以通过了,但我还是想知道是否可以用另一种方法 在一个普通的课堂上,我
customFacade::doSomething()
的每个实例上初始化某些变量,那么这可能吗?我这样做的主要目的是能够存储作为其他对象的变量,并直接对其调用函数。示例为customFacade::client->send()
,在本例中,client
是具有send()
函数的对象的初始化变量。我知道我可以使用一个函数client()
,然后返回对象的一个新实例,这样send()
就可以通过了,但我还是想知道是否可以用另一种方法
在一个普通的课堂上,我可以做下面的事情,但它不适用于正面
$protected client;
public function __construct()
{
$this->client = new instanceOfObject();
}
因为Facade使用静态函数,所以您只能执行以下操作
public static $client = null;
public static function init() {
if(self::$client == null)
self::$client = new instanceOfObject();
}
// somewhere else
customFacade::init();
customFacade::client->send();
Laravel将在服务容器之外,在构成外观基础的类构造函数中解决您需要的所有依赖项。显示我的观点的一个玩具示例将在
DateService
中解析UserRepository
,从而解析Dates
外观
例如
return view('profile' => [
...
'time' => Dates::loggedLocal(),
...
]);
DatetimeService.php
class DatetimeService
{
private $userRepository;
public function __construct(
UserRepository $userRepository
) {
$this->userRepository = $userRepository;
}
/**
* Get the logged in users local time
*
* @return Carbon
*/
public function loggedLocal() : Carbon
{
$user = $this->userRepository->current();
return Carbon::now()->setTimezone($user->timezone);
}
Dates.php
class Dates extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor() { return 'date-service'; }
}
DateServiceProvider.php
class DateServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
$this->app->singleton('date-service', function()
{
return new DateTimeService;
});
}
}
那么什么是底层类,实例,这个facade首先是它的代理?