Laravel:在BaseController构造中使用的beforeFilter不能在子类中工作

时间:2015-02-10 20:38:24

标签: php laravel routing

我阅读了Laravel关于controller filters的文档。我希望将此功能正确应用于我的 BaseController ,因此扩展它的所有控制器都可以自动运行beforeFilter。但是,需要排除其中两条路线。排除的路线名为主页注销,但下面的代码不起作用:classess扩展BaseController会忽略customFilter。我做错了什么?

routes.php文件:

Route::get('/',
    array(
        'before' => 'auth',
        'uses' => 'DefaultController@index',
        'as' => 'home'
        )
    );

Route::get('/logout',
    array(
        'before' => 'auth',
        'uses' => 'UserController@logout',
        'as' => 'logout'
        )
    );

Route::get('/profile',
    array(
        'before' => 'auth',
        'uses' => 'UserController@profile',
        'as' => 'profile'
        )
    );

/// And so on...

BaseController.php:

<?php

    class BaseController extends Controller {

        // beforeFilter to be inherited by subclasses
        public function __construct() {
            $this->beforeFilter('customFilter', array('except' => array('home', 'logout')));
        }

        // Rest of the code

    }

?>

以及稍后(例如)

<?php

class UserController extends BaseController {

    // Code...

}

?>

1 个答案:

答案 0 :(得分:1)

您必须在子类中构造父类,如下所示:

class UserController extends BaseController {

   public function __construct(){
     parent::__construct();
   }

}