>  기사  >  백엔드 개발  >  windFramework_interception 체인

windFramework_interception 체인

WBOY
WBOY원래의
2016-08-08 09:22:12883검색
<?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_interception 체인을 그 측면을 포함하여 소개했습니다. PHP 튜토리얼에 관심이 있는 친구들에게 도움이 되기를 바랍니다.

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.