Home >Backend Development >PHP Tutorial >yii2 Essay (7) Dependency Injection - (2) Simple Implementation of PHP Dependency Injection

yii2 Essay (7) Dependency Injection - (2) Simple Implementation of PHP Dependency Injection

黄舟
黄舟Original
2017-01-17 10:33:491338browse

We knew the problem earlier, so how does PHP solve this problem? Because it is yii2, we use yii2 to briefly introduce it. I integrated the core code of yii2 to explain the process of dependency injection in PHP.

Those who have used yii2 development are familiar with Yii::createObject. It is an "entry" for dependency injection. I will bring it up and change it:

//$p 可以想象的yii2的配置文件,如$p = ['class'=>'sdk/Test', 'file'=>'xxxx'];
// 'class' 是将要实现的类,‘file’是将要实现的对象的属性
function createObject($p){
    $class = $p['class'];
    unset($p['class']);
    $obj = new $class;//require 使用的是 autoload 实现的
    foreach($p as $f => $v){
        $class->$f = $v;    
    }

    return $obj;

Of course, yii2 createObject is far more than that. I wrote it so simply just to illustrate a way for PHP to implement "dependency injection". Of course, it is very rudimentary (it does not have the most basic fault-tolerant function, and it does not have all the functions of dependency injection. For example, parameter management, compatible closures, etc., these will all emerge when we actually look at the yii2 DI implementation).

The above is the content of yii2 Essay (7) Dependency Injection - (2) Simple implementation of PHP dependency injection. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn