过滤器是一段代码,可被配置在控制器动作执行之前或之后执行。例如, 访问控制过滤器将被执行以确保在执行请求的动作之前用户已通过身份验证;性能过滤器可用于测量控制器执行所用的时间。
一个动作可以有多个过滤器。过滤器执行顺序为它们出现在过滤器列表中的顺序。过滤器可以阻止动作及后面其他过滤器的执行。
来客框架的过滤器有几种写法,我暂时只讲解一种,其余的需要童鞋们自行摸索:
基于自定义过滤器类(Filter)的过滤器
无论哪种过滤器,都必须在控制器中重写控制器的public function execute()方法,设置哪个过滤器对哪个动作起作用。
可以在 LKT/webapp/filter 找到系统默认的一些过滤器(LoginFilter.class.php、SedFilter.class.php、ThdFilter.class.php)
我们现在分析一下LoginFilter.class.php代码,如图:
<?php class LoginFilter extends Filter { public $effect; public $candirect = array("Default","Login") ; public function execute ($filterChain) { if($this->effect == false){ $filterChain->execute(); return; } //取得第一个访问模块的名称 $controller = $this->getContext()->getController(); $actionstack = $controller->getActionStack(); $first = $actionstack->getFirstEntry(); $firstmodule = $first->getModuleName(); if(in_array($firstmodule,$this->candirect)){ $filterChain->execute(); } else { if($this->getContext()->getUser()->isAuthenticated()){ $filterChain->execute(); } else { $controller->redirect("index.php?module=Login"); } } return; } public function initialize ($context, $params = null) { if($params['effect']){ $this->effect = true; } else { $this->effect = false; } // initialize parent parent::initialize($context, $params); return true; } } ?>
通过读execute()方法里面的代码,我们可以大概了解这个过滤器的意思,“判断用户是否登录,如果用户没有执行过登录操作,并且登录成功,那么过滤器会直接将你的请求跳转到登录页面,否则继续往下去执行”,其中有一段代码:
public $candirect = array(“Default”,”Login”) ;
也就是在该数组里面的目录可以不经过用户的登录操作直接进入,这些目录对应的是LKT/webapp/modules下面的文件夹名称,如果我们要在modules里面创建一个helloworld目录,并且想直接不用登录授权就能访问,那么我们需要如下配置:
public $candirect = array(“Default”,”Login”,“helloworld”) ;
现在自定义过滤器已经创建好了,接下来,我们需要在哪里配置这个过滤器呢?
LKT/webapp/config/filters.ini
[ExecutionTimeFilter] class = "ExecutionTimeFilter" param.comment = "On" [LoginFilter] file = "filter/LoginFilter.class.php" class = "LoginFilter" param.effect = "On" [ThdFilter] file = "filter/ThdFilter.class.php" class = "ThdFilter" param.effect = "On" [SedFilter] file = "filter/SedFilter.class.php" class = "SedFilter" param.effect = "On"
框架会按照你配置的过滤器依次执行的哦!