Yii中特殊行为ActionFilter的使用方法示例

2022-07-29,,,

新建 app\filters\loggingfilter 继承 yii\base\actionfilter

loggingfilter 的功能: 在指定请求的 action 前后各记录一条日志

<?php

namespace app\filters;

use yii\base\actionfilter;

class loggingfilter extends actionfilter
{
 public function beforeaction($action)
 {
  parent::beforeaction($action);

  // to do something
  printf('this is a logging for %s\beforeaction.%s', $this->getactionid($action), php_eol);

  return true;
 }

 public function afteraction($action, $result)
 {
  parent::afteraction($action, $result);

  // to do something
  printf('this is a logging for %s\afteraction.%s', $this->getactionid($action), php_eol);

  return true;
 }
}

新建 app\controllers\systemcontroller

<?php

namespace app\controllers;

use app\filters\loggingfilter;

class systemcontroller extends \yii\web\controller
{
 public function behaviors()
 {
  parent::behaviors();

  return [
   'anchorauth' => [
    'class' => loggingfilter::classname(),
    'only' => ['test', 'test-one'], // 仅对 'test'、'test-one' 生效
    'except' => ['test-one'], // 排除 'test-one'
   ],
  ];
 }

 public function actiontestone()
 {
  printf('this is a testing for %s.%s', $this->getroute(), php_eol);
 }

 public function actiontesttwo()
 {
  printf('this is a testing for %s.%s', $this->getroute(), php_eol);
 }

 public function actiontest()
 {
  printf('this is a testing for %s.%s', $this->getroute(), php_eol);
 }
}

测试

请求

this is a logging for test\beforeaction.
this is a testing for system/test.
this is a logging for test\afteraction.

请求

this is a testing for system/test-one.

请求

this is a testing for system/test-two.

总结

yii 中的 actionfilter(过滤器)相当于 laravel 中的 middleware(中间件),beforeaction 相当于前置中间件,afteraction 相当于后置中间件。

到此这篇关于yii中特殊行为actionfilter使用的文章就介绍到这了,更多相关yii特殊行为actionfilter使用内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

《Yii中特殊行为ActionFilter的使用方法示例.doc》

下载本文的Word格式文档,以方便收藏与打印。