gpt4 book ai didi

Laravel 自定义 Facade 新实例

转载 作者:行者123 更新时间:2023-12-05 04:12:28 24 4
gpt4 key购买 nike

在处理我的第一个 laravel 包时遇到了我的 Facade 工作方式的问题,目前我的使用看起来像这样:

{!! Custom::showValue() !}} //returns "default"

{!! Custom::setValue('test')->showValue() !}} //returns "test"

{!! Custom::showValue() !}} //returns "test"

我希望最后一个元素成为一个新的类实例,因为我在设置服务提供者时使用了绑定(bind)而不是单例:

public function register()
{
$this->registerCustom();
}

public function registerCustom(){
$this->app->bind('custom',function() {
return new Custom();
});
}

我还需要做些什么才能使对“自定义”的每个外观调用都返回一个新的类实例吗?

最佳答案

正如@maiorano84 提到的,您不能使用开箱即用的Facades 来做到这一点。

要回答您的问题,要使您的 Custom facade 返回一个新实例,您可以向其添加以下方法:

/**
* 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 自定义 Facade 新实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40306354/

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