新建app\filters\LoggingFilter继承yii\base\ActionFilterLoggingFilter的功能:在指定请求的动作之前各记录一条日志getActionId($action),PHP_EOL);返回真;}publicfunctionafterAction($action,$result){parent::afterAction($action,$result);//做一些事情printf('这是%s\afterAction.%s',$this->getActionId($action),PHP_EOL);返回真;}}新建app\controllers\SystemController['class'=>LoggingFilter::className(),'only'=>['test','test-one'],//仅对'test','test-one'有效'except'=>['test-one'],//排除'test-one'],];}publicfunctionactionTestOne(){printf('这是对%s.%s的测试',$this->getRoute(),PHP_EOL);}publicfunctionactionTestTwo(){printf('这是对%s.%s的测试',$this->getRoute(),PHP_EOL);}publicfunctionactionTest(){printf('这是对%s.%s的测试',$this->getRoute(),PHP_EOL);}}测试请求http://yii.test/index.php?r=system/test这是一个测试\beforeAction的日志记录。这是一个系统/测试的测试。这是test\afterAction的日志记录。请求http://yii.test/index.php?r=system/test-one这是对system/test-one的测试。请求http://yii.test/index.php?r=system/test-two这是对system/test-two的测试。总结Yii中的ActionFilter(过滤器)相当于Laravel中的Middleware(中间件),beforeAaction相当于前置中间件,afterAction相当于后置中间件。原文链接https://github.com/guanguans/guanguans.github.io#PHP
