Reputation: 2943
Working on my first laravel package and running into trouble with how my Facade works, currently my use looks something like this:
{!! Custom::showValue() !}} //returns "default"
{!! Custom::setValue('test')->showValue() !}} //returns "test"
{!! Custom::showValue() !}} //returns "test"
I would expect the last element to go be a new class instance, as I've used bind instead of singleton when setting up my service provider:
public function register()
{
$this->registerCustom();
}
public function registerCustom(){
$this->app->bind('custom',function() {
return new Custom();
});
}
Is there something else I need to do to make it so every facade call to "Custom" returns a new class instance?
Upvotes: 4
Views: 1388
Reputation: 1435
From laravel 9 you can use the $cached = false
property inside your facade so it does not get cached:
class YourFacade extends Facade
{
protected static $cached = false;
protected static function getFacadeAccessor()
{
return ...;
}
}
Upvotes: 2
Reputation: 35200
As @maiorano84 mentioned you can not do this with Facades
out of the box.
To answer your question, to make your Custom
facade return a new instance you could add the following method to it:
/**
* Resolve a new instance for the facade
*
* @return mixed
*/
public static function refresh()
{
static::clearResolvedInstance(static::getFacadeAccessor());
return static::getFacadeRoot();
}
Then you could call:
Custom::refresh()->showValue();
(Obviously, you can call refresh
something else if you want to)
One alternative to this would be to use the app()
global function that comes with Laravel to resolve a new instance i.e.
app('custom')->showValue();
Hope this helps!
Upvotes: 3