Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  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. return $container->get($class, [], $reference);
  113. } elseif (empty($reference)) {
  114. throw new InvalidConfigException('The required component is not specified.');
  115. }
  116. if (is_string($reference)) {
  117. $reference = new static($reference);
  118. } elseif ($type === null || $reference instanceof $type) {
  119. return $reference;
  120. }
  121. if ($reference instanceof self) {
  122. $component = $reference->get($container);
  123. if ($type === null || $component instanceof $type) {
  124. return $component;
  125. } else {
  126. throw new InvalidConfigException('"' . $reference->id . '" refers to a ' . get_class($component) . " component. $type is expected.");
  127. }
  128. }
  129. $valueType = is_object($reference) ? get_class($reference) : gettype($reference);
  130. throw new InvalidConfigException("Invalid data type: $valueType. $type is expected.");
  131. }
  132. /**
  133. * Returns the actual object referenced by this Instance object.
  134. * @param ServiceLocator|Container $container the container used to locate the referenced object.
  135. * If null, the method will first try `Yii::$app` then `Yii::$container`.
  136. * @return object the actual object referenced by this Instance object.
  137. */
  138. public function get($container = null)
  139. {
  140. if ($container) {
  141. return $container->get($this->id);
  142. }
  143. if (Yii::$app && Yii::$app->has($this->id)) {
  144. return Yii::$app->get($this->id);
  145. } else {
  146. return Yii::$container->get($this->id);
  147. }
  148. }
  149. }