PHP实现AOP

1,214 阅读1分钟

AOP全称(Aspect Oriented Programming)面向切片编程的简称。
AOP的定义: AOP通过预编译方式和运行期动态代理实现,在不修改源代码的情况下,给程序动态统一添加功能的一种技术,简称AOP。
在API实现过程中,希望将业务实现和其他的诸如权限验证、日志记录等辅助操作进行解耦,这样在进行辅助功能调整的时候对业务实现的影响就较小。
part01:业务实现

<?php
class someService{
    public function todo(){
        //业务逻辑
    }
}

part02:辅助包装

<?php
class AOP{
    private $instance;
    public function __construct($instance){
        $this->instance = $instance;
    }
    
    public function __call($method,$params){
        if(!method_exist($this->instance,$method)){
            throw new Exception("Call undefined method ".get_class($this->instance)."::$method");
        }
        $this->before();
        $callback = array($this->instance,$method);
        $return = call_user_func_array($callback,$params);
        $this->after();
        return $return;
    }
    
    public function before(){
        //验证
    }
    
    public function after(){
        //日志
    }
}

part03:调度工厂

<?php

class serviceFactory{
    public function getSomeServiceInstance(){
        return new AOP(new someService());
    }
}


part04:业务调用

<?php

$someService = servieFactory::getSomeServiceInstance();
$someService->todo();