3

他のすべてのコントローラーがそれを拡張するベースコントローラーがあります。いくつかのテーマと検証を行い、Before 関数にウィジェットをロードしたいと考えています。

これを Routes フィルターで処理できることはわかっていますが、ルーター内にコードを配置したくありません。すべてのコントローラー アクションで最初に「関数の前」を実行し、次に 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にアクセスしたいのです。

4

1 に答える 1

8

ドキュメントによると、コントローラーで before メソッドと after メソッドを 2 つの方法で定義できます。

フィルター名を使用:

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

}
于 2013-05-01T12:10:36.760 に答える