I am working my way through a Yii tutorial book and am currently learning about filters. Filters can be applied in general for the controller or just to specific actions.
The example I am working on is creating a new Issue. Each Issue belongs to a single Project, so we add a filter to ensure the project_id is passed to the issue/create page. Since the issue/create is the only page that needs the project_id, we are applying the filter to a single action:
public function filters(){
return array(
'accessControl', // perform access control for CRUD operations
'projectContext + create',//check to ensure valid project context
);
}
My question is this: If a filter only applies to a single action in the controller, why not just put the filterProjectContext() code directly into the actionCreate() function?
According the yii docs, and my experience with other frameworks, filters are not meant to be coupled with actions. Rather, filters allow you the ability to access PHP globals such as
$_REQUESTvalues before they reach any actions. For example, I worked on a project where we wanted to highlight all translated text if a url parameter was passed with a specific value. We could have done this in the controller but felt it was better to implement the business rule within a filter. The filter ended up looking like:The beauty of the filter is that this code would be executed regardless of which action was requested. My suggestion is that you don’t co-mingle filter logic with action logic.