Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Custom Facade New Instance

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?

like image 514
kilrizzy Avatar asked Oct 20 '25 13:10

kilrizzy


1 Answers

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!

like image 188
Rwd Avatar answered Oct 22 '25 03:10

Rwd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!