Instance.php 6.9 KB

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