http://www.cnitblog.com/fanyh/archive/2010/03/18/64720.html
PHP中的攔截器設計
<?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的意思呢?