我有一个大胆的想法,就是在某某方法执行前与执行后会自动执行某些函数,实现如下:
class 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 "".$id."";
}
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 " update ".$id."";
}
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 "
";
$hook->update(1);
效果图如下:
以上就是一个钩子方法的简单实现,具体可根据该实例变化出更多用法~~~