Http://www.cnitblog.com/fanyh/archive/2010/03/18/64720.html
Interceptor design in PHP
<? PHP
Class action {
Public Function perform (){
Echo 'hello, fanyh! <Br> ';
}
}
/**
* Interceptor Interface
* @ Author Administrator
*
*/
Interface interceptor {
/**
* Run the command before the specified method.
*/
Public Function dobefore ();
/**
* Run the following command after the specified method.
*/
Public Function doafter ();
}
/**
* All basic interceptor classes
* @ 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 ();
}
}
/**
* Define an interceptor
* @ Author Administrator
*
*/
Class interceptorimpl1 extends actinterceptor {
/**
*
*/
Public Function dobefore (){
Echo 'before method ....... 111111111111111111 <br> ';
}
/**
*
*/
Public Function doafter (){
Echo 'after method ....... 1111111111111111111 <br> ';
}
}
/**
* Define an interceptor
* @ Author Administrator
*
*/
Class interceptorimpl2 extends actinterceptor {
/**
*
*/
Public Function dobefore (){
Echo 'before method ....... 2222222222222 <br> ';
}
/**
*
*/
Public Function doafter (){
Echo 'after method ....... 22222222222222222 <br> ';
}
}
/**
* Controller class, used as the interceptor container
* @ Author Administrator
*
*/
Class controller {
Private $ interceptors = array ();
Private $ Index = 0;
/**
* Call the method in Interceptor to execute
*/
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 ();
}
}
/**
* Added 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 ();
?>
Code running result:
Before method ....... 111111111111111111
Before method ....... 2222222222222
Hello, fanyh!
After method ....... 22222222222222222
After method ....... 1111111111111111111
Analysis:
When developing the MVC mode, you can use this method to process all the data before the action is executed, and then process the data after the action.
Does Java mean AOP?