PHP中的攔截器設計

來源:互聯網
上載者:User
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的意思呢?

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.