Google News
logo
Yii framework - Interview Questions
What is Creating Filters in Yii Framework?
To create a new action filter, extend from yii\base\ActionFilter and override the beforeAction() and/or afterAction() methods. The former will be executed before an action runs while the latter after an action runs. The return value of beforeAction() determines whether an action should be executed or not. If it is false, the filters after this one will be skipped and the action will not be executed.
 
The following example shows a filter that logs the action execution time :
namespace app\components;

use Yii;
use yii\base\ActionFilter;

class ActionTimeFilter extends ActionFilter
{
    private $_startTime;

    public function beforeAction($action)
    {
        $this->_startTime = microtime(true);
        return parent::beforeAction($action);
    }

    public function afterAction($action, $result)
    {
        $time = microtime(true) - $this->_startTime;
        Yii::debug("Action '{$action->uniqueId}' spent $time second.");
        return parent::afterAction($action, $result);
    }
}
Advertisement