2013-05-01 35 views
3

我有一個基本控制器,所有其他控制器將擴展它。 我想做一些主題和驗證,並在其Before函數中加載小部件。Laravel 4控制器之前和之後功能

我知道我可以用路由過濾器來處理這個,但是我不想把我的代碼放在路由器裏我想讓每個控制器的動作先執行「Before function」然後執行這個Base控制器的「After function」 Laravel 3.

class FrontController extends \BaseController { 
    protected $layout = 'home.index'; 
    public function __construct() { 
    } 

    public function before() { 
     // Do some theme and validation 
    } 


    public function __call($method, $parameters) { 

     return Response::abort('404'); 
    } 

更新:我正在尋找一種方式,例如,我可以基於頁面的配置或負載側邊欄小工具更換主題後,主控制器完成了它的功能和......因爲我想訪問$ this。

回答

8

根據documentation,您可以通過兩種方式在控制器中的方法前後定義。

隨着過濾器名稱:

$this->beforeFilter('auth'); 
$this->afterFilter('something_else'); 

或封閉:

$this->beforeFilter(function() { 
    // code 
}); 

這些會去你的基地控制器的方法__construct

這裏有一個完整的例子:

class BaseController extends Controller { 

    public function __construct() 
    { 
     // Always run csrf protection before the request when posting 
     $this->beforeFilter('csrf', array('on' => 'post')); 

     // Here's something that happens after the request 
     $this->afterFilter(function() { 
      // something 
     }); 
    } 

    /** 
    * Setup the layout used by the controller. 
    * 
    * @return void 
    */ 
    protected function setupLayout() 
    { 
     if (! is_null($this->layout)) 
     { 
      $this->layout = View::make($this->layout); 
     } 
    } 

} 
+0

謝謝本傑明但問題是,當我們使用封閉,我們不能使用$,因爲我們不在對象範圍內。 例如,這將引發異常: 公共函數__construct(){$ 這 - >後過濾器(功能(){ 的var_dump($這個 - >佈局); }); } – 2013-05-01 14:04:58

+1

@MiladRey您可以將參數傳遞給封閉 – 2013-05-01 16:03:02

+0

我嘗試這樣做: 公共職能__construct(){$ 這 - > beforeFilter(函數($ OBJ)使用($這個){ 的var_dump($ obj- > layout); }); } 但它拋出 「編譯錯誤:無法使用$該詞法變量」 – 2013-05-01 18:31:28