Instance.php 5.41 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\di;

use Yii;
use yii\base\InvalidConfigException;

/**
14
 * Instance represents a reference to a named object in a dependency injection (DI) container or a service locator.
15
 *
16
 * You may use [[get()]] to obtain the actual object referenced by [[id]].
17 18 19
 *
 * Instance is mainly used in two places:
 *
20 21 22
 * - When configuring a dependency injection container, you use Instance to reference a class name, interface name
 *   or alias name. The reference can later be resolved into the actual object by the container.
 * - In classes which use service locator to obtain dependent objects.
23
 *
24
 * The following example shows how to configure a DI container with Instance:
25 26
 *
 * ```php
27 28 29 30 31 32
 * $container = new \yii\di\Container;
 * $container->set('cache', 'yii\caching\DbCache', Instance::of('db'));
 * $container->set('db', [
 *     'class' => 'yii\db\Connection',
 *     'dsn' => 'sqlite:path/to/file.db',
 * ]);
33 34
 * ```
 *
35
 * And the following example shows how a class retrieves a component from a service locator:
36 37
 *
 * ```php
38
 * class DbCache extends Cache
39
 * {
40
 *     public $db = 'db';
41 42 43
 *
 *     public function init()
 *     {
44
 *         parent::init();
45 46 47 48 49 50 51 52 53 54 55
 *         $this->db = Instance::ensure($this->db, 'yii\db\Connection');
 *     }
 * }
 * ```
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class Instance
{
    /**
56
     * @var string the component ID, class name, interface name or alias name
57 58 59
     */
    public $id;

60

61 62 63 64
    /**
     * Constructor.
     * @param string $id the component ID
     */
Qiang Xue committed
65
    protected function __construct($id)
66 67 68 69 70 71 72 73 74
    {
        $this->id = $id;
    }

    /**
     * Creates a new Instance object.
     * @param string $id the component ID
     * @return Instance the new Instance object.
     */
Qiang Xue committed
75
    public static function of($id)
76
    {
Qiang Xue committed
77
        return new static($id);
78 79 80
    }

    /**
81
     * Resolves the specified reference into the actual object and makes sure it is of the specified type.
82
     *
83 84
     * The reference may be specified as a string or an Instance object. If the former,
     * it will be treated as a component ID, a class/interface name or an alias, depending on the container type.
85
     *
86
     * If you do not specify a container, the method will first try `Yii::$app` followed by `Yii::$container`.
87 88 89 90 91 92 93 94
     *
     * For example,
     *
     * ```php
     * use yii\db\Connection;
     *
     * // returns Yii::$app->db
     * $db = Instance::ensure('db', Connection::className());
95 96
     * // returns an instance of Connection using the given configuration
     * $db = Instance::ensure(['dsn' => 'sqlite:path/to/my.db'], Connection::className());
97 98
     * ```
     *
99
     * @param object|string|array|static $reference an object or a reference to the desired object.
100
     * You may specify a reference in terms of a component ID or an Instance object.
101 102
     * Starting from version 2.0.2, you may also pass in a configuration array for creating the object.
     * If the "class" value is not specified in the configuration array, it will use the value of `$type`.
103 104 105 106
     * @param string $type the class/interface name to be checked. If null, type check will not be performed.
     * @param ServiceLocator|Container $container the container. This will be passed to [[get()]].
     * @return object the object referenced by the Instance, or `$reference` itself if it is an object.
     * @throws InvalidConfigException if the reference is invalid
107
     */
108
    public static function ensure($reference, $type = null, $container = null)
109
    {
110 111
        if ($reference instanceof $type) {
            return $reference;
112 113 114
        } elseif (is_array($reference)) {
            $class = isset($reference['class']) ? $reference['class'] : $type;
            if (!$container instanceof Container) {
Qiang Xue committed
115
                $container = Yii::$container;
116 117 118
            }
            unset($reference['class']);
            return $container->get($class, [], $reference);
119
        } elseif (empty($reference)) {
Qiang Xue committed
120 121 122
            throw new InvalidConfigException('The required component is not specified.');
        }

123 124
        if (is_string($reference)) {
            $reference = new static($reference);
125 126
        }

127 128
        if ($reference instanceof self) {
            $component = $reference->get($container);
Qiang Xue committed
129
            if ($component instanceof $type || $type === null) {
130 131
                return $component;
            } else {
132
                throw new InvalidConfigException('"' . $reference->id . '" refers to a ' . get_class($component) . " component. $type is expected.");
133 134
            }
        }
Qiang Xue committed
135

136
        $valueType = is_object($reference) ? get_class($reference) : gettype($reference);
Qiang Xue committed
137
        throw new InvalidConfigException("Invalid data type: $valueType. $type is expected.");
138 139 140
    }

    /**
141 142 143 144
     * Returns the actual object referenced by this Instance object.
     * @param ServiceLocator|Container $container the container used to locate the referenced object.
     * If null, the method will first try `Yii::$app` then `Yii::$container`.
     * @return object the actual object referenced by this Instance object.
145
     */
Qiang Xue committed
146
    public function get($container = null)
147
    {
Qiang Xue committed
148
        if ($container) {
149
            return $container->get($this->id);
Qiang Xue committed
150 151 152
        }
        if (Yii::$app && Yii::$app->has($this->id)) {
            return Yii::$app->get($this->id);
153
        } else {
Qiang Xue committed
154
            return Yii::$container->get($this->id);
155 156 157
        }
    }
}