Instance.php 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\di;
  8. use Yii;
  9. use yii\base\InvalidConfigException;
  10. /**
  11. * Instance represents a reference to a named object in a dependency injection (DI) container or a service locator.
  12. *
  13. * You may use [[get()]] to obtain the actual object referenced by [[id]].
  14. *
  15. * Instance is mainly used in two places:
  16. *
  17. * - When configuring a dependency injection container, you use Instance to reference a class name, interface name
  18. * or alias name. The reference can later be resolved into the actual object by the container.
  19. * - In classes which use service locator to obtain dependent objects.
  20. *
  21. * The following example shows how to configure a DI container with Instance:
  22. *
  23. * ```php
  24. * $container = new \yii\di\Container;
  25. * $container->set('cache', [
  26. * 'class' => 'yii\caching\DbCache',
  27. * 'db' => Instance::of('db')
  28. * ]);
  29. * $container->set('db', [
  30. * 'class' => 'yii\db\Connection',
  31. * 'dsn' => 'sqlite:path/to/file.db',
  32. * ]);
  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. * public function init()
  43. * {
  44. * parent::init();
  45. * $this->db = Instance::ensure($this->db, 'yii\db\Connection');
  46. * }
  47. * }
  48. * ```
  49. *
  50. * @author Qiang Xue <qiang.xue@gmail.com>
  51. * @since 2.0
  52. */
  53. class Instance
  54. {
  55. /**
  56. * @var string the component ID, class name, interface name or alias name
  57. */
  58. public $id;
  59. /**
  60. * Constructor.
  61. * @param string $id the component ID
  62. */
  63. protected function __construct($id)
  64. {
  65. $this->id = $id;
  66. }
  67. /**
  68. * Creates a new Instance object.
  69. * @param string $id the component ID
  70. * @return Instance the new Instance object.
  71. */
  72. public static function of($id)
  73. {
  74. return new static($id);
  75. }
  76. /**
  77. * Resolves the specified reference into the actual object and makes sure it is of the specified type.
  78. *
  79. * The reference may be specified as a string or an Instance object. If the former,
  80. * it will be treated as a component ID, a class/interface name or an alias, depending on the container type.
  81. *
  82. * If you do not specify a container, the method will first try `Yii::$app` followed by `Yii::$container`.
  83. *
  84. * For example,
  85. *
  86. * ```php
  87. * use yii\db\Connection;
  88. *
  89. * // returns Yii::$app->db
  90. * $db = Instance::ensure('db', Connection::className());
  91. * // returns an instance of Connection using the given configuration
  92. * $db = Instance::ensure(['dsn' => 'sqlite:path/to/my.db'], Connection::className());
  93. * ```
  94. *
  95. * @param object|string|array|static $reference an object or a reference to the desired object.
  96. * You may specify a reference in terms of a component ID or an Instance object.
  97. * Starting from version 2.0.2, you may also pass in a configuration array for creating the object.
  98. * If the "class" value is not specified in the configuration array, it will use the value of `$type`.
  99. * @param string $type the class/interface name to be checked. If null, type check will not be performed.
  100. * @param ServiceLocator|Container $container the container. This will be passed to [[get()]].
  101. * @return object the object referenced by the Instance, or `$reference` itself if it is an object.
  102. * @throws InvalidConfigException if the reference is invalid
  103. */
  104. public static function ensure($reference, $type = null, $container = null)
  105. {
  106. if (is_array($reference)) {
  107. $class = isset($reference['class']) ? $reference['class'] : $type;
  108. if (!$container instanceof Container) {
  109. $container = Yii::$container;
  110. }
  111. unset($reference['class']);
  112. $component = $container->get($class, [], $reference);
  113. if ($type === null || $component instanceof $type) {
  114. return $component;
  115. }
  116. throw new InvalidConfigException('Invalid data type: ' . $class . '. ' . $type . ' is expected.');
  117. } elseif (empty($reference)) {
  118. throw new InvalidConfigException('The required component is not specified.');
  119. }
  120. if (is_string($reference)) {
  121. $reference = new static($reference);
  122. } elseif ($type === null || $reference instanceof $type) {
  123. return $reference;
  124. }
  125. if ($reference instanceof self) {
  126. try {
  127. $component = $reference->get($container);
  128. } catch (\ReflectionException $e) {
  129. throw new InvalidConfigException('Failed to instantiate component or class "' . $reference->id . '".', 0, $e);
  130. }
  131. if ($type === null || $component instanceof $type) {
  132. return $component;
  133. }
  134. throw new InvalidConfigException('"' . $reference->id . '" refers to a ' . get_class($component) . " component. $type is expected.");
  135. }
  136. $valueType = is_object($reference) ? get_class($reference) : gettype($reference);
  137. throw new InvalidConfigException("Invalid data type: $valueType. $type is expected.");
  138. }
  139. /**
  140. * Returns the actual object referenced by this Instance object.
  141. * @param ServiceLocator|Container $container the container used to locate the referenced object.
  142. * If null, the method will first try `Yii::$app` then `Yii::$container`.
  143. * @return object the actual object referenced by this Instance object.
  144. */
  145. public function get($container = null)
  146. {
  147. if ($container) {
  148. return $container->get($this->id);
  149. }
  150. if (Yii::$app && Yii::$app->has($this->id)) {
  151. return Yii::$app->get($this->id);
  152. }
  153. return Yii::$container->get($this->id);
  154. }
  155. /**
  156. * Restores class state after using `var_export()`.
  157. *
  158. * @param array $state
  159. * @return Instance
  160. * @throws InvalidConfigException when $state property does not contain `id` parameter
  161. * @see var_export()
  162. * @since 2.0.12
  163. */
  164. public static function __set_state($state)
  165. {
  166. if (!isset($state['id'])) {
  167. throw new InvalidConfigException('Failed to instantiate class "Instance". Required parameter "id" is missing');
  168. }
  169. return new self($state['id']);
  170. }
  171. }