Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use static variables in Laravel Facades

I have a Facade (in this case a singleton) and I register it using a ServiceProvider:

Service Provider

use App;

class FacilityServiceProvider extends ServiceProvider 
{

    public function register()
    {  
        $this->app->singleton('Facility', function(){
            return new Facility();
        });

        // Shortcut so developers don't need to add an Alias in app/config/app.php
        $this->app->booting(function()
        {
            $loader = \Illuminate\Foundation\AliasLoader::getInstance();
            $loader->alias('Facility', 'CLG\Facility\Facades\FacilityFacade');
        });
    }
}

Facade

use Illuminate\Support\Facades\Facade;

class FacilityFacade extends Facade {

    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor() { return 'Facility'; }
}

Now, I want to have static variables inside my Facility class:

Facility.php

class Facility
{
    public static $MODEL_NOT_FOUND = '-1';

    public function __construct() { ... }
}

but when I use Facility::$MODEL_NOT_FOUND, I get Access to undeclared static property.

What am I doing wrong?

like image 615
Kousha Avatar asked Dec 06 '25 17:12

Kousha


1 Answers

That's because the Facade class only "redirects" method calls to the underlying class. So you can't access properties directly. The simplest solution is using a getter method.

class Facility
{
    public static $MODEL_NOT_FOUND = '-1';

    public function __construct() { ... }

    public function getModelNotFound(){
        return self::$MODEL_NOT_FOUND;
    }
}

The alternative would be to write your own Facade class that extends from Illuminate\Support\Facades\Facade and make use of magic methods to access properties directly

like image 166
lukasgeiter Avatar answered Dec 08 '25 06:12

lukasgeiter



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!