php aop切编程(勾子与行为)

文章讨论了两种在面向切面编程中实现方法调用拦截的方法:一种是使用__call魔术方法,另一种是通过CALL机制。这两种方法都涉及在目标方法前后执行自定义逻辑。

时间:2019-08-07 09:44:53

  1. 方法一(映射)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

/**

 * @param $name

 * @param $arguments

 * @return mixed|void

 * @throws ReflectionException

 */

public function __call($name$arguments){

    //判断方法是否存在

    if (!method_exists(get_called_class(), $name)){

        return;

    }

    //判断权限

    //日志

    //调用方法

    $class new ReflectionClass(get_called_class());

    $instance $class->newInstance();

    $method $class->getMethod($name);

    $method->setAccessible(true);

    return $method->invoke($instance);

}

  1. 方法二(CALL)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

         * 不管用什么样的方式实现的AOP类,这部分逻辑是一样的,    

         * 执行目标方法之前,运行一些对象,(可有可无)    

         * 执行目标方法    

         * 执行目标方法之后,运行一些对象。(可有可无)    

         *     

         * 中间件, 代理, 都是同样的作用    

         */    

        try{    

            // before    

            if(isset($this->calls[$method]['before'])){    

                foreach ($this->calls[$method]['before'as  $value) {    

                    // if(!is_callable($value, $params)){    

                    //     throw new Exception("call error", 1);    

                    // }    

                    call_user_func_array($value$params);    

                }    

            }    

            $ret = call_user_func_array([$this->realSubject, $method], $params);    

            // $ret = $this->realSubject->$method($params);    

            //after    

            if(isset($this->calls[$method]['after'])){    

                foreach ($this->calls[$method]['after'as  $value) {    

                    call_user_func_array($value$params);    

                }    

            }    

        }catch(\Exception $e) {    

            exit($e->getMessage());    

        }    

        return $ret;        /**

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值