我有一個大膽的想法,就是在某某方法執行前與執行後會自動執行某些函數,實現如下:
<?phpclass Hook {protected $targetClass;public function setTargetClass($classObj) {$this->targetClass = $classObj;}private function invoker($name, $arguments) {if(method_exists($this->targetClass, 'before_'.$name)) call_user_func_array([$this->targetClass, 'before_'.$name], $arguments);call_user_func_array([$this->targetClass, $name], $arguments);if(method_exists($this->targetClass, 'after_'.$name)) call_user_func_array([$this->targetClass, 'after_'.$name], $arguments);}public function __call($name, $arguments) {// TODO:Implemnt __call() method$this->invoker($name, $arguments);}}class Other {public function index($id) {echo "</br>".$id."</br>";}public function before_index($id) {echo 'other before index $id='.$id;}public function after_index($id) {echo 'other after index $id='.$id;}public function update($id) {echo "</br> update ".$id."</br>";}public function before_update($id) {echo 'other before update $id='.$id;}// public function after_update($id) {// echo 'other before after $id='.$id;// }}$hook = new Hook();$obj = new Other();$hook->setTargetClass($obj);$hook->index(1);echo "<hr>";$hook->update(1);
效果圖如下:
以上就是一個鉤子方法的簡單實現,具體可根據該執行個體變化出更多用法~~~