您的位置:首页 > 编程语言 > PHP开发

php 使用__call实现钩子方法

2017-05-22 09:55 507 查看
我有一个大胆的想法,就是在某某方法执行前与执行后会自动执行某些函数,实现如下:

<?php
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 "</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);
效果图如下:



以上就是一个钩子方法的简单实现,具体可根据该实例变化出更多用法~~~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: