Examples of using actionfilter with special behavior in Yii

Time:2021-4-23

newly buildapp\filters\LoggingFilterinherityii\base\ActionFilter

Loggingfilter function: record a log before and after the action of the specified request

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

newly buildapp\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'] // only valid for 'test' and 'test-one'
                'except' = > ['test-one '], // exclude' 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);
    }
}

test

requesthttp://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.

requesthttp://yii.test/index.php?r=system/test-one

This is a testing for system/test-one.

requesthttp://yii.test/index.php?r=system/test-two

This is a testing for system/test-two.

summary

In YiiActionFilter(filter) is equivalent to that in laravelMiddleware(Middleware),beforeActionIt is equivalent to the front middleware,afterActionIt is equivalent to post middleware.

Original link

Recommended Today

Implementation example of go operation etcd

etcdIt is an open-source, distributed key value pair data storage system, which provides shared configuration, service registration and discovery. This paper mainly introduces the installation and use of etcd. Etcdetcd introduction etcdIt is an open source and highly available distributed key value storage system developed with go language, which can be used to configure sharing […]