Filters in Yii

Yii FiltersFilter is a piece of code that is configured to be executed before and/or after a controller action executes. For example, an access control filter may be executed to ensure that the user is authenticated before executing the requested action; a performance filter

may be used to measure the time spent executing the action.
An action can have multiple filters. The filters are executed in the order that they appear in the filter list. A filter can prevent the execution of the action and the rest of the unexecuted filters.
There are two types of filter

  1. controller Method filter
  2. class based filter

Controller Method Filter
A Filter can be defined as a controller method. The method name must begin with filter
e.g

 public function filterEnforcelogin($filterChain) { if(Yii::app()->user->isGuest) { throw new CHttpException(403,"you must login first"); } $filterChain->run(); }

where $filterChain is an instance of CFilterChain which represents the filter list associated with the requested action. Inside the method, we have to call $filterChain->run() to continue filter and action execution.
In order to implement this filter we have to override the filter method in the controller.
As given below here we specify the filter enforcelogin which we want to execute to check whether the visitor is guest or logged in user.But here we specify –ve sign with the action.It shows that we want to exclude these methods from the filter process.But if we use + sign it means we want to include only those methods for filter process.we can specify the action one after the another using space or using comma.

public function filters() { return array('enforcelogin -error login'); }

Class Based Filter
In class based filter we create the filter class by extending it from the CFilter class.It can be used across multiple controllers (generic filter).In filter class two methods are specified .Prefilter action executed before any controller action and it returns true if filter criteria is fullfilled in order to allow the other filter processing to execute .class based filter are implemented similar to the method based filter.But they are specified within a array.

class EnforceLoginFilter extends CFilter { protected function preFilter($filterChain) { if(Yii::app()->user->isGuest) { throw new CHttpException(403,"you must login first"); return false; }else return true; // false if the action should not be executed } protected function postFilter($filterChain) { // logic being applied after the action is executed } } public function filters() { return array( array('application.components.EnforceLoginFilter -error login')); }

4 thoughts on “Filters in Yii”

  1. why have u not mentioned that

    public function filters() { return array( array(‘application.components.EnforceLoginFilter -error login’)); }

    should be written in respective controller.. it cant be in the class which extends the cfilter.

Leave a Reply