PHP实现动态代理

码农天地 -
PHP实现动态代理
对接第三方时需要重试,使用反射简单写了一个重试代理,上代码:
class Retry {

    /**
     * @var object 代理对象
     */
    private $__proxy;

    /**
     * @var int 重试一次
     */
    private $__retry_times = 1;

    /**
     * @var int 延迟一秒
     */
    private $__delay_time = 1000000;

    /**
     * @param $name
     * @param $args
     * @return mixed
     * @throws Exception
     */
    public function __call($name, $args){

        if(!method_exists($this->get_proxy(), $name)){
            throw new Exception('cannot found method.');
        }

        $times = 0;

        $reflection = new ReflectionClass($this->get_proxy());
        $method = $reflection->getMethod($name);

        if (!$method->isPublic() || $method->isAbstract()) {
            throw new Exception('method is not public or is abstract.');
        }

        while ($times < $this->get_retry_times()){
            try{
                $res = $method->invokeArgs($this->get_proxy(), $args);
                return $res;
            }catch (Exception $e){
                $times++;
                if($times >= $this->__retry_times){
                    throw $e;
                }
                usleep($this->get_delay_microseconds());
            }
        }
    }

    public function set_proxy($real_subject){
        $this->__proxy = $real_subject;
    }

    public function get_proxy(){
        return $this->__proxy;
    }

    public function set_retry_times($retry_times){
        $this->__retry_times = $retry_times;
    }

    public function get_retry_times(){
        return $this->__retry_times;
    }

    public function set_delay_microseconds($delay_time){
        $this->__delay_time = $delay_time;
    }

    public function get_delay_microseconds(){
        return $this->__delay_time;
    }
}
核心其实就是反射的invokeArgs函数,但是网上一搜都是使用的invoke,还真是挺搞笑了。
特别申明:本文内容来源网络,版权归原作者所有,如有侵权请立即与我们联系(cy198701067573@163.com),我们将及时处理。

php介绍

PHP即“超文本预处理器”,是一种通用开源脚本语言。PHP是在服务器端执行的脚本语言,与C语言类似,是常用的网站编程语言。PHP独特的语法混合了C、Java、Perl以及 PHP 自创的语法。利于学习,使用广泛,主要适用于Web开发领域。

Tags 标签

php动态代理反射

扩展阅读

加个好友,技术交流

1628738909466805.jpg