<?php class Action{ public function perform(){ echo 'hello,fanyh!<br>' ; } } /** * Interceptor接口 * @author Administrator * */ interface Interceptor{ /** * 在指定的方法之前执行 */ public function doBefore() ; /** * 在指定的方法之后 执行 */ public function doAfter() ; } /** * 所有Interceptor的基类 * @author Administrator * */ abstract class AbstractInterceptor implements Interceptor{ public final function invoke($object,$method,$args=null){ $this->doBefore() ; if(method_exists($object,$method)){ $object->$method($args); } $this->doAfter() ; } } /** * 定义一个Interceptor * @author Administrator * */ class InterceptorImpl1 extends AbstractInterceptor{ /** * */ public function doBefore() { echo 'Before method......111111111111111111<br>' ; } /** * */ public function doAfter() { echo 'After method......1111111111111111111<br>' ; } } /** * 定义一个Interceptor * @author Administrator * */ class InterceptorImpl2 extends AbstractInterceptor{ /** * */ public function doBefore() { echo 'Before method......2222222222222<br>' ; } /** * */ public function doAfter() { echo 'After method......22222222222222222<br>' ; } } /** * 控制器类,同时作为Interceptor的容器 * @author Administrator * */ class Controller{ private $interceptors = array(); private $index = 0 ; /** * 调用Interceptor中的方法来执行 */ public function invoke(){ if ($this->index<count($this->interceptors)){ $this->interceptors[$this->index++]->invoke($this,'invoke') ; }else{ $this->index = 0 ; $action = new Action() ; $action->perform() ; } } /** * 增加Interceptor * @param unknown_type $interceptor */ public function addInterceptor($interceptor){ $this->interceptors[] = $interceptor ; } } $controller = new Controller() ; $controller->addInterceptor(new InterceptorImpl1()) ; $controller->addInterceptor(new InterceptorImpl2()) ; $controller->invoke() ; ?>
代码运行结果: Before method......111111111111111111 Before method......2222222222222 hello,fanyh! After method......22222222222222222 After method......1111111111111111111 分 析: 在实现MVC模式开发时,可以利用这种方式在action执行前对数据做一切处理,在经过action后再加处理 是不是有点java 中的AOP的意思呢?