随笔-3  评论-2  文章-0  trackbacks-0

<?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的意思呢?

posted on 2010-03-18 21:08 fanyh 阅读(1783) 评论(2)  编辑 收藏 引用 所属分类: PHP

评论:
# re: PHP中的拦截器设计 2010-03-19 12:23 | 凡客诚品衬衫
按时间多哈见到大三  回复  更多评论
  
# re: PHP中的拦截器设计 2011-10-12 10:34 | 漂漂
你好,麻烦问下,这个拦截器如何在项目中使用呢?java的拦截器是自动触发使用的,这个php拦截器如何在每个action请求的时候自动调用呢?  回复  更多评论
  
只有注册用户登录后才能发表评论。