Laravel 自定义外观新实例
Laravel Custom Facade New Instance
在我的第一个 laravel 包上工作并且 运行 遇到了我的 Facade 工作方式的问题,目前我的使用看起来像这样:
{!! Custom::showValue() !}} //returns "default"
{!! Custom::setValue('test')->showValue() !}} //returns "test"
{!! Custom::showValue() !}} //returns "test"
我希望最后一个元素成为新的 class 实例,因为我在设置服务提供商时使用了绑定而不是单例:
public function register()
{
$this->registerCustom();
}
public function registerCustom(){
$this->app->bind('custom',function() {
return new Custom();
});
}
我还需要做些什么才能让每个外观调用 "Custom" returns 一个新的 class 实例吗?
正如@maiorano84 提到的那样,开箱即用 Facades
无法做到这一点。
要回答您的问题,要使您的 Custom
门面 return 成为一个新实例,您可以向其添加以下方法:
/**
* Resolve a new instance for the facade
*
* @return mixed
*/
public static function refresh()
{
static::clearResolvedInstance(static::getFacadeAccessor());
return static::getFacadeRoot();
}
那么您可以拨打:
Custom::refresh()->showValue();
(显然,如果你愿意,你可以调用 refresh
其他东西)
另一种方法是使用 Laravel 附带的 app()
全局函数来解析新实例,即
app('custom')->showValue();
希望对您有所帮助!
从 laravel 9 开始,您可以在外观中使用 $cached = false
属性,这样它就不会被缓存:
class YourFacade extends Facade
{
protected static $cached = false;
protected static function getFacadeAccessor()
{
return ...;
}
}
在我的第一个 laravel 包上工作并且 运行 遇到了我的 Facade 工作方式的问题,目前我的使用看起来像这样:
{!! Custom::showValue() !}} //returns "default"
{!! Custom::setValue('test')->showValue() !}} //returns "test"
{!! Custom::showValue() !}} //returns "test"
我希望最后一个元素成为新的 class 实例,因为我在设置服务提供商时使用了绑定而不是单例:
public function register()
{
$this->registerCustom();
}
public function registerCustom(){
$this->app->bind('custom',function() {
return new Custom();
});
}
我还需要做些什么才能让每个外观调用 "Custom" returns 一个新的 class 实例吗?
正如@maiorano84 提到的那样,开箱即用 Facades
无法做到这一点。
要回答您的问题,要使您的 Custom
门面 return 成为一个新实例,您可以向其添加以下方法:
/**
* Resolve a new instance for the facade
*
* @return mixed
*/
public static function refresh()
{
static::clearResolvedInstance(static::getFacadeAccessor());
return static::getFacadeRoot();
}
那么您可以拨打:
Custom::refresh()->showValue();
(显然,如果你愿意,你可以调用 refresh
其他东西)
另一种方法是使用 Laravel 附带的 app()
全局函数来解析新实例,即
app('custom')->showValue();
希望对您有所帮助!
从 laravel 9 开始,您可以在外观中使用 $cached = false
属性,这样它就不会被缓存:
class YourFacade extends Facade
{
protected static $cached = false;
protected static function getFacadeAccessor()
{
return ...;
}
}