Yii2 之ServiceLocator 和Container 类

技巧库 · wy1272086709 · 于 6年前 发布 · 5810 次阅读

先看一段本地的php测试代码

 public function actionIndex4()
    {
        \Yii::$container->setSingleton('app\models\Account');
        $var = \Yii::createObject('app\models\Account');
        $var2 = \Yii::createObject('app\models\Account');
        $db = \Yii::$app->getDb();
        $db2 = \Yii::$app->getDb();
        \Yii::$app->set('test','app\models\Account');
        $t1 = \Yii::$app->get('test');
        $t2 = \Yii::$app->get('test'); 
        if($var===$var2)
            echo '1';
        if($var==$var2)
            echo '2';
        if($db===$db2)
        {
            echo '3';
        }
        if($t1===$t2)
        {
            echo '4';
        }
        exit('ffff');
    }

最后输出结果为1234ffff Yii::$app 这里最后得到的是Aplication类的对象 这个对象是继承自ServiceLocator类的,这个类有对应的set和get方法,用于生成单例类。Yii::createObject 这种方式调用的是Container 类的get方法.container 类的get 方法生成的类不是单例的.但是可以通过.Container 类的setSingleton方法和get方法来生成单例类 从具体代码可以看出.

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 {
            return null;
        }
    }
	public function set($id, $definition)
    {
        if ($definition === 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'])) {
                $this->_definitions[$id] = $definition;
            } else {
                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));
        }
    }
共收到 2 条回复
forecho#16年前 0 个赞

排版有待加强

@forecho #1楼 嗯 在学习中.

添加回复 (需要登录)
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册