Use static variables in Laravel Facades

14.6k views Asked by At

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?

1

There are 1 answers

4
lukasgeiter On BEST ANSWER

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