3

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?

Kousha
  • 32,871
  • 51
  • 172
  • 296

1 Answers1

6

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

lukasgeiter
  • 147,337
  • 26
  • 332
  • 270
  • Yeah I thought so too. What I don't like then is that I would have to call it as a function, and not a variable (i.e. `Facility::getModelNotFound()` rather than `Facility::$ModelNotFound` or whatever the name is). What do you recommend? – Kousha Dec 07 '14 at 21:39
  • You won't get around calling a function with Laravel's Facade class. However as I mentioned. You could write your own. Give me some time... I'm going to write one and update the answer. – lukasgeiter Dec 07 '14 at 21:42
  • Ouh well... I thought it would be possible with something like `__getStatic()` but apparently there's no thing like that. You have to work with methods or no Facade at all :/ – lukasgeiter Dec 07 '14 at 21:59
  • Haha, okay thanks. I guess I'm stuck with function name – Kousha Dec 07 '14 at 22:05