Home  >  Article  >  Backend Development  >  yii2 Essay (7) Dependency Injection - (4) Service Locator

yii2 Essay (7) Dependency Injection - (4) Service Locator

黄舟
黄舟Original
2017-01-17 10:38:221339browse

Service locator locator is a solution to dependency injection. It includes dependency injection. After dependency injection is solved, if the service user and service provider are not the same person, then the user must understand the method of providing the service. Parameters are required to ensure the correctness of dependencies, which couples users and providers. The service locator decouples this part. The service provider registers the service in the ServiceLocator (and registers the dependencies at the same time), and only tells the service to use or the names or aliases of those services, then it is good for both service providers and users. Users only need to know what services the provider provides, but do not need to know what they depend on, and service providers do not need to "use them randomly" for users. "Troubled by bugs caused by service.

So how does yii2 use ServiceLocator? In fact, it is very simple as follows

//魔术方法,
public function __get($name){
    //得到某个注册的方法
    if ($this->has($name)) {
        return $this->get($name);
    } else {
        return parent::__get($name);
    }
}
//魔术方法查看某个服务是否存在,源码略
public function __isset($name){}
//__isset()中调用,查看某个服务是否存在,源码略
public function has($id, $checkInstance = false){}
//得到某个服务
public function get($id, $throwException = true)
{
    if (isset($this->_components[$id])) {//如果是已经处理的服务,就直接返回
        return $this->_components[$id];
    }

    if (isset($this->_definitions[$id])) {//如定义了该服务
        $definition = $this->_definitions[$id];//得到服务的定义
        //如果服务是一个闭包,则把闭包注册到已经实例化的服务中,并且返回闭包
        if (is_object($definition) && !$definition instanceof Closure) {
            return $this->_components[$id] = $definition;
        } else {//其他的情况下通过依赖注入生成对象,并且注册为已处理,返回对象
            return $this->_components[$id] = Yii::createObject($definition);
        }
    } elseif ($throwException) {//如果抛出异常,则抛出异常
        throw new InvalidConfigException("Unknown component ID: $id");
    } else {//其他返回null
        return null;
    }
}
//注册一个服务
public function set($id, $definition)
{
    if ($definition === null) {//如果该服务的定义为null,则删除已经实例化的服务,返回空,用于注销已经实例化的并且保存过的服务的定义
        unset($this->_components[$id], $this->_definitions[$id]);
        return;
    }
    //清空已经实例化的服务
    unset($this->_components[$id]);
    //如果该服务的定义为一个对象,并且是一个可调用的结构
    if (is_object($definition) || is_callable($definition, true)) {
        // an object, a class name, or a PHP callable
        $this->_definitions[$id] = $definition;
    } elseif (is_array($definition)) {//如果该服务是一个配置数组
        // a configuration array
        if (isset($definition['class'])) {//如果有class键值,则直接注册为一个服务的定义
            $this->_definitions[$id] = $definition;
        } else {//是配置数组,但是没有指定class,则抛出异常
            throw new InvalidConfigException("The configuration for the \"$id\" component must contain a \"class\" element.");
        }
    } else {//什么都不是,抛出异常,非法注册服务
        throw new InvalidConfigException("Unexpected configuration type for the \"$id\" component: " . gettype($definition));
    }
}
//清空已经实例化过的服务和定义,代码略
public function clear($id){}
//得到已经实例化后的服务,或者得到可用的服务配置
public function getComponents($returnDefinitions = true){}
//注册所有的服务,这里的$components,就是你在config里写的 $config['components']值
public function setComponents($components){}

So when did ServiceLocator get involved? Let's continue to open our index.php, pay attention to the following sentence

(new yii\web\Application($config))->run();

Let's check Application

class Application extends \yii\base\Application
//继续追踪  \yii\base\Application
abstract class Application extends Module
//继续追踪  Module
class Module extends ServiceLocator
Ha, finally found it! ! ! Our application is actually a service locator. The components we configure in the configuration file are all services registered by the service locator of the application. Now you know why the function is called setComponents. If you don’t understand, continue reading.

yii uses the set[typename] function to ensure the writability of attributes. Yii::configure($this, $config); is used in the constructor of the base class yii\base\Object; this will Call the setComponents function to register the service.

Okay, we have contacted each other before and after. That’s all for the dependency injection and service locator used by yii2.

The above is the yii2 essay (7) Dependency Injection - (4) The content of the service locator. 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