2014-12-07 21 views
1

我有一個門面(在這種情況下單),我就用ServiceProvider註冊:使用在Laravel外立面靜態變量

服務提供商

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'); 
     }); 
    } 
} 

門面

use Illuminate\Support\Facades\Facade; 

class FacilityFacade extends Facade { 

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

現在,我想在我的Facility類中有靜態變量:

Facility.php

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

    public function __construct() { ... } 
} 

但是當我使用Facility::$MODEL_NOT_FOUND,我得到Access to undeclared static property

我在做什麼錯?

回答

2

這是因爲Facade類只對基礎類「重定向」方法調用。所以你不能直接訪問屬性。最簡單的解決方案是使用getter方法。

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

    public function __construct() { ... } 

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

另一種方法是編寫從Illuminate\Support\Facades\Facade擴展自己的門面類,並利用magic methods直接訪問屬性

+0

是啊,我也這麼認爲。然後我不喜歡的是,我不得不把它稱爲函數,而不是變量(即'Facility :: getModelNotFound()'而不是'Facility :: $ ModelNotFound'或任何名稱)。你有什麼建議? – Kousha 2014-12-07 21:39:43

+0

你不會在Laravel的Facade類中調用一個函數。但正如我所說的。你可以自己寫。給我一些時間...我要寫一個並更新答案。 – lukasgeiter 2014-12-07 21:42:21

+0

呃呃...我認爲這可能會像'__getStatic()',但顯然沒有這樣的事情。你必須使用方法或根本沒有Facade:/ – lukasgeiter 2014-12-07 21:59:51