首页 > 后端开发 > php教程 > PHP 依赖注入,从此不再考虑加载顺序,从此不再加载_PHP教程

PHP 依赖注入,从此不再考虑加载顺序,从此不再加载_PHP教程

WBOY
发布: 2016-07-12 09:00:40
原创
693 人浏览过

PHP 依赖注入,从此不再考虑加载顺序,从此不再加载

说这个话题之前先讲一个比较高端的思想--'依赖倒置原则'

"依赖倒置是一种软件设计思想,在传统软件中,上层代码依赖于下层代码,当下层代码有所改动时,上层代码也要相应进行改动,因此维护成本较高。而依赖倒置原则的思想是,上层不应该依赖下层,应依赖接口。意为上层代码定义接口,下层代码实现该接口,从而使得下层依赖于上层接口,降低耦合度,提高系统弹性"

 

上面的解释有点虚,下面我们以实际代码来解释这个理论

比如有这么条需求,用户注册完成后要发送一封邮件,然后你有如下代码:

先有邮件类'Email.class.php'

<span>class</span> <span>Mail</span><span>{
    </span><span>public</span> <span>function</span><span> send()
    {
        </span><span>/*</span><span>这里是如何发送邮件的代码</span><span>*/</span><span>
    }
}</span>
登录后复制

然后又注册的类'Register.class.php'

<span>class</span><span> Register{
    </span><span>private</span> <span>$_emailObj</span><span>;

    </span><span>public</span> <span>function</span><span> doRegister()
    {
        </span><span>/*</span><span>这里是如何注册</span><span>*/</span>

        <span>$this</span>->_emailObj = <span>new</span> <span>Mail</span><span>();
        </span><span>$this</span>->_emailObj->send();<span>//</span><span>发送邮件</span>
<span>    }
}</span>
登录后复制

然后开始注册

<span>include</span> 'Mail.class.php'<span>;
</span><span>include</span> 'Register.class.php'<span>;
</span><span>$reg</span> = <span>new</span><span> Register();
</span><span>$reg</span>->doRegister();
登录后复制

看起来事情很简单,你很快把这个功能上线了,看起来相安无事... xxx天过后,产品人员说发送邮件的不好,要使用发送短信的,然后你说这简单我把'Mail'类改下...

又过了几天,产品人员说发送短信费用太高,还是改用邮件的好... 此时心中一万个草泥马奔腾而过...

这种事情,常常在产品狗身上发生,无可奈何花落去...

以上场景的问题在于,你每次不得不对'Mail'类进行修改,代码复用性很低,高层过度依赖于底层。那么我们就考虑'依赖倒置原则',让底层继承高层制定的接口,高层依赖于接口。

<span>interface</span> <span>Mail</span><span>
{
    </span><span>public</span> <span>function</span><span> send();
}</span>
登录后复制
<span>class</span> Email <span>implements</span> <span>Mail</span><span>()
{
    </span><span>public</span> <span>function</span><span> send()
    {
        </span><span>//</span><span>发送Email</span>
<span>    }
}</span>
登录后复制
<span>class</span> SmsMail <span>implements</span> <span>Mail</span><span>()
{
    </span><span>public</span> <span>function</span><span> send()
    {
        </span><span>//</span><span>发送短信</span>
<span>    }
}</span>
登录后复制
<span>class</span><span> Register
{
    </span><span>private</span> <span>$_mailObj</span><span>;

    </span><span>public</span> <span>function</span> __construct(<span>Mail</span> <span>$mailObj</span><span>)
    {
        </span><span>$this</span>->_mailObj = <span>$mailObj</span><span>;
    }

    </span><span>public</span> <span>function</span><span> doRegister()
    {
        </span><span>/*</span><span>这里是如何注册</span><span>*/</span>
        <span>$this</span>->_mailObj->send();<span>//</span><span>发送信息</span>
<span>    }
}</span>
登录后复制

下面开始发送信息

<span>/*</span><span> 此处省略若干行 </span><span>*/</span>
<span>$reg</span> = <span>new</span><span> Register();
</span><span>$emailObj</span> = <span>new</span><span> Email();
</span><span>$smsObj</span> = <span>new</span><span> SmsMail();

</span><span>$reg</span>->doRegister(<span>$emailObj</span>);<span>//</span><span>使用email发送</span>
<span>$reg</span>->doRegister(<span>$smsObj</span>);<span>//</span><span>使用短信发送</span><span>
/*</span><span> 你甚至可以发完邮件再发短信 </span><span>*/</span>
登录后复制

上面的代码解决了'Register'对信息发送类的依赖,使用构造函数注入的方法,使得它只依赖于发送短信的接口,只要实现其接口中的'send'方法,不管你怎么发送都可以。上例就使用了"注入"这个思想,就像注射器一样将一个类的实例注入到另一个类的实例中去,需要用什么就注入什么。当然"依赖倒置原则"也始终贯彻在里面。"注入"不仅可以通过构造函数注入,也可以通过属性注入,上面你可以可以通过一个"setter"来动态为"mailObj"这个属性赋值。

上面看了很多,但是有心的读者可能会发现标题中"从此不再考虑加载顺序"这个字眼,你上面的不还是要考虑加载顺序吗? 不还是先得引入信息发送类,然后在引入注册类,然后再实例化吗? 如果类一多,不照样晕!

确实如此,现实中有许多这样的案例,一开始类就那么多,慢慢的功能越来越多,人员越来越多,编写了很多类,要使用这个类必须先引入那个类,而且一定要确保顺序正确。有这么个例子, "a 依赖于b, b 依赖于c, c 依赖于 d, d 依赖于e", 要获取'a'的实例,你必须依次引入 'e,d,c,b'然后依次进行实例化,老的员工知道这个坑,跳过去了。某天来了个新人,他想实例化'a' 可是一直报错,他都不造咋回事,此时只能看看看'a'的业务逻辑,然后知道要先获取'b'的实例,然后在看'b'的业务逻辑,然后... 一天过去了,他还是没有获取到'a'的实例,然后领导来了...

那这个事情到底是新人的技术低下,还是当时架构人员的水平低下了?

现在切入话题,来实现如何不考虑加载顺序,在实现前就要明白要是不考虑加载顺序就意味着让程序自动进行加载自动进行实例化。类要实例化,只要保证完整的传递给'__construct'函数所必须的参数就OK了,在类中如果要引用其他类,也必须在构造函数中注入,否则调用时仍然会发生错误。那么我们需要一个类,来保存类实例化所需要的参数,依赖的其他类或者对象以及各个类实例化后的引用

该类命名为盒子 'Container.class.php', 其内容如下:

<span>/*</span><span>*
*    依赖注入类
</span><span>*/</span>
<span>class</span><span> Container{
    </span><span>/*</span><span>*
    *@var array 存储各个类的定义  以类的名称为键
    </span><span>*/</span>
    <span>private</span> <span>$_definitions</span> = <span>array</span><span>();

    </span><span>/*</span><span>*
    *@var array 存储各个类实例化需要的参数 以类的名称为键
    </span><span>*/</span>
    <span>private</span> <span>$_params</span> = <span>array</span><span>();

    </span><span>/*</span><span>*
    *@var array 存储各个类实例化的引用
    </span><span>*/</span>
    <span>private</span> <span>$_reflections</span> = <span>array</span><span>();

    </span><span>/*</span><span>*
    * @var array 各个类依赖的类
    </span><span>*/</span>
    <span>private</span> <span>$_dependencies</span> = <span>array</span><span>();

    </span><span>/*</span><span>*
    * 设置依赖
    * @param string $class 类、方法 名称
    * @param mixed $defination 类、方法的定义
    * @param array $params 类、方法初始化需要的参数
    </span><span>*/</span>
    <span>public</span> <span>function</span> set(<span>$class</span>, <span>$defination</span> = <span>array</span>(), <span>$params</span> = <span>array</span><span>())
    {
        </span><span>$this</span>->_params[<span>$class</span>] = <span>$params</span><span>;
        </span><span>$this</span>->_definitions[<span>$class</span>] = <span>$this</span>->initDefinition(<span>$class</span>, <span>$defination</span><span>);
    }

    </span><span>/*</span><span>*
    * 获取实例
    * @param string $class 类、方法 名称
    * @param array $params 实例化需要的参数
    * @param array $properties 为实例配置的属性
    * @return mixed
    </span><span>*/</span>
    <span>public</span> <span>function</span> get(<span>$class</span>, <span>$params</span> = <span>array</span>(), <span>$properties</span> = <span>array</span><span>())
    {
        </span><span>if</span>(!<span>isset</span>(<span>$this</span>->_definitions[<span>$class</span><span>]))
        {</span><span>//</span><span>如果重来没有声明过 则直接创建</span>
            <span>return</span> <span>$this</span>->bulid(<span>$class</span>, <span>$params</span>, <span>$properties</span><span>);
        }

        </span><span>$defination</span> = <span>$this</span>->_definitions[<span>$class</span><span>];

        </span><span>if</span>(<span>is_callable</span>(<span>$defination</span>, <span>true</span><span>))
        {</span><span>//</span><span>如果声明是函数</span>
            <span>$params</span> = <span>$this</span>->parseDependencies(<span>$this</span>->mergeParams(<span>$class</span>, <span>$params</span><span>));
            </span><span>$obj</span> = <span>call_user_func</span>(<span>$defination</span>, <span>$this</span>, <span>$params</span>, <span>$properties</span><span>);
        }
        </span><span>elseif</span>(<span>is_array</span>(<span>$defination</span><span>))
        {
            </span><span>$originalClass</span> = <span>$defination</span>['class'<span>];
            </span><span>unset</span>(<span>$definition</span>['class'<span>]);

            </span><span>//</span><span>difinition中除了'class'元素外 其他的都当做实例的属性处理</span>
            <span>$properties</span> = <span>array_merge</span>((<span>array</span>)<span>$definition</span>, <span>$properties</span><span>);

            </span><span>//</span><span>合并该类、函数声明时的参数</span>
            <span>$params</span> = <span>$this</span>->mergeParams(<span>$class</span>, <span>$params</span><span>);
            </span><span>if</span>(<span>$originalClass</span> === <span>$class</span><span>)
            {</span><span>//</span><span>如果声明中的class的名称和关键字的名称相同 则直接生成对象</span>
                <span>$obj</span> = <span>$this</span>->bulid(<span>$class</span>, <span>$params</span>, <span>$properties</span><span>);
            }
            </span><span>else</span><span>
            {</span><span>//</span><span>如果不同则有可能为别名 则从容器中获取</span>
                <span>$obj</span> = <span>$this</span>->get(<span>$originalClass</span>, <span>$params</span>, <span>$properties</span><span>);
            }
        }
        </span><span>elseif</span>(<span>is_object</span>(<span>$defination</span><span>))
        {</span><span>//</span><span>如果是个对象 直接返回</span>
            <span>return</span> <span>$defination</span><span>;
        }
        </span><span>else</span><span>
        {
            </span><span>throw</span> <span>new</span> <span>Exception</span>(<span>$class</span> . ' 声明错误!'<span>);
        }
        </span><span>return</span> <span>$obj</span><span>;
    }

    </span><span>/*</span><span>*
    * 合并参数
    * @param string $class 类、函数 名称
    * @param array $params 参数
    * @return array
    </span><span>*/</span>
    <span>protected</span> <span>function</span> mergeParams(<span>$class</span>, <span>$params</span> = <span>array</span><span>())
    {
        </span><span>if</span>(<span>empty</span>(<span>$this</span>->_params[<span>$class</span><span>]))
        {
            </span><span>return</span> <span>$params</span><span>;
        }
        </span><span>if</span>(<span>empty</span>(<span>$params</span><span>))
        {
            </span><span>return</span> <span>$this</span>-><span>_params;
        }

        </span><span>$result</span> = <span>$this</span>->_params[<span>$class</span><span>];
        </span><span>foreach</span>(<span>$params</span> <span>as</span> <span>$key</span> => <span>$value</span><span>) 
        {
            </span><span>$result</span>[<span>$key</span>] = <span>$value</span><span>;
        }
        </span><span>return</span> <span>$result</span><span>;
    }

    </span><span>/*</span><span>*
    * 初始化声明
    * @param string $class 类、函数 名称
    * @param array $defination 类、函数的定义
    * @return mixed
    </span><span>*/</span>
    <span>protected</span> <span>function</span> initDefinition(<span>$class</span>, <span>$defination</span><span>)
    {
        </span><span>if</span>(<span>empty</span>(<span>$defination</span><span>))
        {
            </span><span>return</span> <span>array</span>('class' => <span>$class</span><span>);
        }
        </span><span>if</span>(<span>is_string</span>(<span>$defination</span><span>))
        {
            </span><span>return</span> <span>array</span>('class' => <span>$defination</span><span>);
        }
        </span><span>if</span>(<span>is_callable</span>(<span>$defination</span>) || <span>is_object</span>(<span>$defination</span><span>))
        {
            </span><span>return</span> <span>$defination</span><span>;
        }
        </span><span>if</span>(<span>is_array</span>(<span>$defination</span><span>))
        {
            </span><span>if</span>(!<span>isset</span>(<span>$defination</span>['class'<span>]))
            {
                </span><span>$definition</span>['class'] = <span>$class</span><span>;
            }
            </span><span>return</span> <span>$defination</span><span>;
        }
        </span><span>throw</span> <span>new</span> <span>Exception</span>(<span>$class</span>. ' 声明错误'<span>);
    }

    </span><span>/*</span><span>*
    * 创建类实例、函数
    * @param string $class 类、函数 名称
    * @param array $params 初始化时的参数
    * @param array $properties 属性
    * @return mixed
    </span><span>*/</span>
    <span>protected</span> <span>function</span> bulid(<span>$class</span>, <span>$params</span>, <span>$properties</span><span>)
    {
        </span><span>list</span>(<span>$reflection</span>, <span>$dependencies</span>) = <span>$this</span>->getDependencies(<span>$class</span><span>);

        </span><span>foreach</span> ((<span>array</span>)<span>$params</span> <span>as</span> <span>$index</span> => <span>$param</span><span>) 
        {</span><span>//</span><span>依赖不仅有对象的依赖 还有普通参数的依赖</span>
            <span>$dependencies</span>[<span>$index</span>] = <span>$param</span><span>;
        }

        </span><span>$dependencies</span> = <span>$this</span>->parseDependencies(<span>$dependencies</span>, <span>$reflection</span><span>);

        </span><span>$obj</span> = <span>$reflection</span>->newInstanceArgs(<span>$dependencies</span><span>);

        </span><span>if</span>(<span>empty</span>(<span>$properties</span><span>))
        {
            </span><span>return</span> <span>$obj</span><span>;
        }

        </span><span>foreach</span> ((<span>array</span>)<span>$properties</span> <span>as</span> <span>$name</span> => <span>$value</span><span>) 
        {
            </span><span>$obj</span>-><span>$name</span> = <span>$value</span><span>;
        }

        </span><span>return</span> <span>$obj</span><span>;
    }

    </span><span>/*</span><span>*
    * 获取依赖
    * @param string $class 类、函数 名称
    * @return array
    </span><span>*/</span>
    <span>protected</span> <span>function</span> getDependencies(<span>$class</span><span>)
    {
        </span><span>if</span>(<span>isset</span>(<span>$this</span>->_reflections[<span>$class</span><span>]))
        {</span><span>//</span><span>如果已经实例化过 直接从缓存中获取</span>
            <span>return</span> <span>array</span>(<span>$this</span>->_reflections[<span>$class</span>], <span>$this</span>->_dependencies[<span>$class</span><span>]);
        }

        </span><span>$dependencies</span> = <span>array</span><span>();
        </span><span>$ref</span> = <span>new</span> ReflectionClass(<span>$class</span>);<span>//</span><span>获取对象的实例</span>
        <span>$constructor</span> = <span>$ref</span>->getConstructor();<span>//</span><span>获取对象的构造方法</span>
        <span>if</span>(<span>$constructor</span> !== <span>null</span><span>)
        {</span><span>//</span><span>如果构造方法有参数</span>
            <span>foreach</span>(<span>$constructor</span>->getParameters() <span>as</span> <span>$param</span><span>) 
            {</span><span>//</span><span>获取构造方法的参数</span>
                <span>if</span>(<span>$param</span>-><span>isDefaultValueAvailable())
                {</span><span>//</span><span>如果是默认 直接取默认值</span>
                    <span>$dependencies</span>[] = <span>$param</span>-><span>getDefaultValue();
                }
                </span><span>else</span><span>
                {</span><span>//</span><span>将构造函数中的参数实例化</span>
                    <span>$temp</span> = <span>$param</span>-><span>getClass();
                    </span><span>$temp</span> = (<span>$temp</span> === <span>null</span> ? <span>null</span> : <span>$temp</span>-><span>getName());
                    </span><span>$temp</span> = Instance::getInstance(<span>$temp</span>);<span>//</span><span>这里使用Instance 类标示需要实例化 并且存储类的名字</span>
                    <span>$dependencies</span>[] = <span>$temp</span><span>;
                }
            }
        }
        </span><span>$this</span>->_reflections[<span>$class</span>] = <span>$ref</span><span>;
        </span><span>$this</span>->_dependencies[<span>$class</span>] = <span>$dependencies</span><span>;
        </span><span>return</span> <span>array</span>(<span>$ref</span>, <span>$dependencies</span><span>);
    }

    </span><span>/*</span><span>*
    * 解析依赖
    * @param array $dependencies 依赖数组
    * @param array $reflection 实例
    * @return array $dependencies
    </span><span>*/</span>
    <span>protected</span> <span>function</span> parseDependencies(<span>$dependencies</span>, <span>$reflection</span> = <span>null</span><span>)
    {
        </span><span>foreach</span> ((<span>array</span>)<span>$dependencies</span> <span>as</span> <span>$index</span> => <span>$dependency</span><span>) 
        {
            </span><span>if</span>(<span>$dependency</span><span> instanceof Instance)
            {
                </span><span>if</span> (<span>$dependency</span>->id !== <span>null</span><span>) 
                {
                    </span><span>$dependencies</span>[<span>$index</span>] = <span>$this</span>->get(<span>$dependency</span>-><span>id);
                } 
                </span><span>elseif</span>(<span>$reflection</span> !== <span>null</span><span>) 
                {
                    </span><span>$parameters</span> = <span>$reflection</span>->getConstructor()-><span>getParameters();
                    </span><span>$name</span> = <span>$parameters</span>[<span>$index</span>]-><span>getName();
                    </span><span>$class</span> = <span>$reflection</span>-><span>getName();
                    </span><span>throw</span> <span>new</span> <span>Exception</span>('实例化类 ' . <span>$class</span> . ' 时缺少必要参数:' . <span>$name</span><span>);
                }   
            }
        }
        </span><span>return</span> <span>$dependencies</span><span>;
    }
}</span>
登录后复制

下面是'Instance'类的内容,该类主要用于记录类的名称,标示是否需要获取实例

<span>class</span><span> Instance{
    </span><span>/*</span><span>*
     * @var 类唯一标示
     </span><span>*/</span>
    <span>public</span> <span>$id</span><span>;

    </span><span>/*</span><span>*
     * 构造函数
     * @param string $id 类唯一ID
     * @return void
     </span><span>*/</span>
    <span>public</span> <span>function</span> __construct(<span>$id</span><span>)
    {
        </span><span>$this</span>->id = <span>$id</span><span>;
    }

    </span><span>/*</span><span>*
     * 获取类的实例
     * @param string $id 类唯一ID
     * @return Object Instance
     </span><span>*/</span>
    <span>public</span> <span>static</span> <span>function</span> getInstance(<span>$id</span><span>)
    {
        </span><span>return</span> <span>new</span> self(<span>$id</span><span>);
    }
}</span>
登录后复制

然后我们在'Container.class.php'中还是实现了为类的实例动态添加属性的功能,若要动态添加属性,需使用魔术方法'__set'来实现,因此所有使用依赖加载的类需要实现该方法,那么我们先定义一个基础类 'Base.class.php',内容如下

<span>class</span><span> Base{
    </span><span>/*</span><span>*
    * 魔术方法
    * @param string $name
    * @param string $value
    * @return void
    </span><span>*/</span>
    <span>public</span> <span>function</span> __set(<span>$name</span>, <span>$value</span><span>)
    {
        </span><span>$this</span>->{<span>$name</span>} = <span>$value</span><span>;
    }
}</span>
登录后复制

然后我们来实现'A,B,C'类,A类的实例 依赖于 B类的实例,B类的实例依赖于C类的实例

'A.class.php'

<span>class</span> A <span>extends</span><span> Base{
    </span><span>private</span> <span>$instanceB</span><span>;

    </span><span>public</span> <span>function</span> __construct(B <span>$instanceB</span><span>)
    {
        </span><span>$this</span>->instanceB = <span>$instanceB</span><span>;
    }

    </span><span>public</span> <span>function</span><span> test()
    {
        </span><span>$this</span>->instanceB-><span>test();
    }
}</span>
登录后复制

'B.class.php'

<span>class</span> B  <span>extends</span><span> Base{
    </span><span>private</span> <span>$instanceC</span><span>;

    </span><span>public</span> <span>function</span> __construct(C <span>$instanceC</span><span>)
    {
        </span><span>$this</span>->instanceC = <span>$instanceC</span><span>;
    }

    </span><span>public</span> <span>function</span><span> test()
    {
        </span><span>return</span> <span>$this</span>->instanceC-><span>test();
    }
}</span>
登录后复制

'C.class.php'

<span>class</span> C  <span>extends</span><span> Base{
    </span><span>public</span> <span>function</span><span> test()
    {
        </span><span>echo</span> 'this is C!'<span>;
    }
}de</span>
登录后复制

然后我们在'index.php'中获取'A'的实例,要实现自动加载,需要使用SPL类库的'spl_autoload_register'方法,代码如下

<span>function</span> autoload(<span>$className</span><span>)
{
    </span><span>include_once</span> <span>$className</span> . '.class.php'<span>;
}
spl_autoload_register(</span>'autoload', <span>true</span>, <span>true</span><span>);
</span><span>$container</span> = <span>new</span><span> Container;

</span><span>$a</span> = <span>$container</span>->get('A'<span>);
</span><span>$a</span>->test();<span>//</span><span>输出 'this is C!'</span>
登录后复制

上面的例子看起来是不是很爽,根本都不需要考虑'B','C' (当然,这里B,C 除了要使用相应类的实例外,没有其他参数,如果有其他参数,必须显要调用'$container->set(xx)'方法进行注册,为其制定实例化必要的参数)。有细心同学可能会思考,比如我在先获取了'A'的实例,我在另外一个地方也要获取'A'的实例,但是这个地方'A'的实例需要其中某个属性不一样,我怎么做到?

你可以看到'Container' 类的 'get' 方法有其他两个参数,'$params' 和 '$properties' , 这个'$properties' 即可实现刚刚的需求,这都依赖'__set'魔术方法,当然这里你不仅可以注册类,也可以注册方法或者对象,只是注册方法时要使用回调函数,例如

<span>$container</span>->set('foo', <span>function</span>(<span>$container</span>, <span>$params</span>, <span>$config</span><span>){
    </span><span>print_r</span>(<span>$params</span><span>);
    </span><span>print_r</span>(<span>$config</span><span>);
});

</span><span>$container</span>->get('foo', <span>array</span>('name' => 'foo'), <span>array</span>('key' => 'test'));
登录后复制

还可以注册一个对象的实例,例如

<span>class</span><span> Test
{
    </span><span>public</span> <span>function</span><span> mytest()
    {
        </span><span>echo</span> 'this is a test'<span>;
    }
}

</span><span>$container</span>->set('testObj', <span>new</span><span> Test());

</span><span>$test</span> = <span>$container</span>->get('testObj'<span>);
</span><span>$test</span>->mytest();
登录后复制

 

 以上自动加载,依赖控制的大体思想就是将类所要引用的实例通过构造函数注入到其内部,在获取类的实例的时候通过PHP内建的反射解析构造函数的参数对所需要的类进行加载,然后进行实例化,并进行缓存以便在下次获取时直接从内存取得

 

以上代码仅仅用于学习和实验,未经严格测试,请不要用于生产环境,以免产生未知bug

 

鄙人才疏学浅,有不足之处,欢迎补足!

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1092697.htmlTechArticlePHP 依赖注入,从此不再考虑加载顺序,从此不再加载 说这个话题之前先讲一个比较高端的思想--' 依赖倒置原则 ' "依赖倒置是一种软件设计...
相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板