美文网首页
php面向切面编程实现(AOP)

php面向切面编程实现(AOP)

作者: mafa1993 | 来源:发表于2020-04-30 21:31 被阅读0次

php面向切面编程实现

切面编程类似于一层一层的,走完一层在进行另外一层,就例如权限验证,在所有业务逻辑之前都需要进行权限验证,权限后才能执行其他的,这就是切面

话不多说上代码
···php
class BIZ
{
public function foobar(num) { print_r(num);
echo "\n业务逻辑 do something";
}
}

class AOP{
private instance; public function __construct(instance){
//instance 为biz的对象this->instance = $instance;
}

 public function __call($method,$argument) {
      if (!method_exists($this->instance, $method)) {
           throw new Exception('未定义的方法:' . $method);
      }
      echo "\n权限检查"; 
      $callBack = array($this->instance,$method);
      $return = call_user_func($callBack,$argument);
      echo "\n日志记录"; 
      return $return;
 }

}

class Factory
{
public static function getBizInstance()
{
return new AOP(new BIZ());
}
}

try {
obj = Factory::getBizInstance(); //这里要执行BIZ中的内容,必须先执行AOP的内容,不用extend实现 //obj是aop对象 var_dump(obj);
obj->foobar(3); //这里走aop的__call 就是在执行每个方法前, 都要调用aop中的__call, 从而实现一系列的内容 } catch (Exceptione) {
echo 'Exception '.$e->getMessage();
}
···

相关文章

网友评论

      本文标题:php面向切面编程实现(AOP)

      本文链接:https://www.haomeiwen.com/subject/xbtxghtx.html