时间:2021-07-01 10:21:17 帮助过:22人阅读
- <!--?php
- /**
- * 拦截器基类
- */
- class Interceptor{
- /**
- * 保存拦截链
- * 用以传递控制到下一个拦截器
- *
- * @var interceptorChain
- */
- protected $interceptorChain = null;
- /**
- * 拦截器的执行入口
- *
- * @param string 要执行拦截器的方法名
- */
- public function handle($method) {
- //执行拦截器的指定方法
- if (method_exists($this, $method)){
- $this--->$method();
- }
- //取到拦截链中的下一个拦截器
- $handler = $this->interceptorChain->getHandler();
- //递归循环,把所有拦截链中的拦截器都循环一遍,并挨个执行这个方法
- if (null !== $handler){
- $handler->handle($method);
- }
- return;
- }
- /**
- * 设置拦截链对象(用以传递控制到下一个拦截器)
- *
- * @param interceptorChain $interceptorChain
- */
- public function setHandlerInterceptorChain($interceptorChain) {
- $this->interceptorChain = $interceptorChain;
- }
- }
- /**
- * 拦截链
- */
- class interceptorChain{
- /**
- * 拦截器
- * @var array
- */
- protected $_interceptors = array('_Na' => null);
- /**
- * 得到下一个拦截器
- * @return interceptorChain|NULL|Interceptor
- */
- public function getHandler() {
- if (count($this->_interceptors) <= 1) {
- return $this;
- }
- //返回数组指针的下一个指针
- $handler = next($this->_interceptors);
- //如果没有下一个指针,则指针指向第一个元素并返回null
- if ($handler === false) {
- reset($this->_interceptors);
- return null;
- }
- if (method_exists($handler, 'handle')) {
- //设计拦截器基类中的拦截链
- $handler->setHandlerInterceptorChain($this);
- //返回拦截器对象
- return $handler;
- }
- return $this->getHandler();
- }
- /**
- * 往拦截链中添加拦截器
- * @param Interceptor $interceptors
- */
- public function addInterceptors($interceptors) {
- if (is_array($interceptors))
- $this->_interceptors = array_merge($this->_interceptors, $interceptors);
- else
- $this->_interceptors[] = $interceptors;
- }
- /**
- * 重置拦截链初始化信息
- * @return boolean
- */
- public function reset() {
- $this->_interceptors = array('_Na' => null);
- return true;
- }
- }
- //拦截器一
- class InterceptorOne extends Interceptor{
- public function interceptMethod(){
- echo "执行拦截器1中的拦截方法<br>";
- }
- }
- //拦截器二
- class InterceptorTwo extends Interceptor{
- public function interceptMethod(){
- echo "执行拦截器2中的拦截方法<br>";
- }
- }
- //先弄一个拦截链
- $interceptorChain = new interceptorChain();
- //再弄两个拦截器
- $InterceptorOne = new InterceptorOne();
- $InterceptorTwo = new InterceptorTwo();
- //再把拦截器 放到拦截链里面
- $interceptorChain->addInterceptors($InterceptorOne);
- $interceptorChain->addInterceptors($InterceptorTwo);
- //运行拦截链
- $interceptorChain->getHandler()->handle('interceptMethod');
- // 执行拦截器1中的拦截方法
- // 执行拦截器2中的拦截方法
遗留问题:
1,为什么拦截链中默认有一个'_Na'的键位,是做什么的,默认为空数组不就好了?
以上就介绍了windFramework_拦截链,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。