php 简单拦截器,PHP简单拦截器实现方法【参考java的AOP】

本文探讨了在MVC开发中如何使用Interceptor进行数据预处理和后处理,通过InterceptorImpl1和InterceptorImpl2实例展示AOP的面向切面编程特性,类似于Java中的前置通知和后置通知。
摘要由CSDN通过智能技术生成

class Action{

public function perform(){

echo 'hello,fanyh!
' ;

}

}

/**

* 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
' ;

}

/**

*

*/

public function doAfter() {

echo 'After method......1111111111111111111
' ;

}

}

/**

* 定义一个Interceptor

* @author Administrator

*

*/

class InterceptorImpl2 extends AbstractInterceptor{

/**

*

*/

public function doBefore() {

echo 'Before method......2222222222222
' ;

}

/**

*

*/

public function doAfter() {

echo 'After method......22222222222222222
' ;

}

}

/**

* 控制器类,同时作为Interceptor的容器

* @author Administrator

*

*/

class Controller{

private $interceptors = array();

private $index = 0 ;

/**

* 调用Interceptor中的方法来执行

*/

public function invoke(){

if ($this->indexinterceptors)){

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值