當(dāng)前位置:首頁 >  站長 >  編程技術(shù) >  正文

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

 2020-10-22 11:42  來源: 腳本之家   我來投稿 撤稿糾錯

  域名預(yù)訂/競價,好“米”不錯過

這篇文章主要給大家介紹了關(guān)于Yii中特殊行為ActionFilter的使用方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

#FormatStrongID_0#

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

#FormatStrongID_1#

請求 http://yii.test/index.php?r=system/test

This is a logging for test\beforeAction.
This is a testing for system/test.
This is a logging for test\afterAction.

請求 http://yii.test/index.php?r=system/test-one

This is a testing for system/test-one.

請求 http://yii.test/index.php?r=system/test-two

This is a testing for system/test-two.

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

#FormatStrongID_2#

Yii 中的 ActionFilter(過濾器)相當(dāng)于 Laravel 中的 Middleware(中間件),beforeAction 相當(dāng)于前置中間件,afterAction 相當(dāng)于后置中間件。

到此這篇關(guān)于Yii中特殊行為ActionFilter使用的文章就介紹到這了,更多相關(guān)Yii特殊行為ActionFilter使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

來源:腳本之家

鏈接:https://www.jb51.net/article/197626.htm

申請創(chuàng)業(yè)報道,分享創(chuàng)業(yè)好點子。點擊此處,共同探討創(chuàng)業(yè)新機遇!

相關(guān)文章

熱門排行

信息推薦