Commit 87df068e by Qiang Xue

DI WIP

parent 8e11ad03
...@@ -55,7 +55,7 @@ $object = Yii::createObject([ ...@@ -55,7 +55,7 @@ $object = Yii::createObject([
'class' => 'MyClass', 'class' => 'MyClass',
'property1' => 'abc', 'property1' => 'abc',
'property2' => 'cde', 'property2' => 'cde',
], $param1, $param2); ], [$param1, $param2]);
``` ```
......
...@@ -105,13 +105,11 @@ For each component you can specify class-wide defaults. For example, if you want ...@@ -105,13 +105,11 @@ For each component you can specify class-wide defaults. For example, if you want
widgets without specifying the class for every widget usage, you can do the following: widgets without specifying the class for every widget usage, you can do the following:
```php ```php
\Yii::$objectConfig = [ \Yii::$container->set('yii\widgets\LinkPager', [
'yii\widgets\LinkPager' => [ 'options' => [
'options' => [ 'class' => 'pagination',
'class' => 'pagination', ],
], ]);
],
];
``` ```
The code above should be executed once before `LinkPager` widget is used. It can be done in `index.php`, the application The code above should be executed once before `LinkPager` widget is used. It can be done in `index.php`, the application
......
...@@ -71,7 +71,7 @@ $object = Yii::createObject([ ...@@ -71,7 +71,7 @@ $object = Yii::createObject([
'class' => 'MyClass', 'class' => 'MyClass',
'property1' => 'abc', 'property1' => 'abc',
'property2' => 'cde', 'property2' => 'cde',
], $param1, $param2); ], [$param1, $param2]);
``` ```
More on configuration can be found in the [Basic concepts section](basics.md). More on configuration can be found in the [Basic concepts section](basics.md).
......
...@@ -200,10 +200,9 @@ class Mailer extends BaseMailer ...@@ -200,10 +200,9 @@ class Mailer extends BaseMailer
} }
} }
unset($config['constructArgs']); unset($config['constructArgs']);
array_unshift($args, $className); $object = Yii::createObject($className, $args);
$object = call_user_func_array(['Yii', 'createObject'], $args);
} else { } else {
$object = new $className; $object = Yii::createObject($className);
} }
if (!empty($config)) { if (!empty($config)) {
foreach ($config as $name => $value) { foreach ($config as $name => $value) {
......
...@@ -10,6 +10,7 @@ use yii\base\InvalidConfigException; ...@@ -10,6 +10,7 @@ use yii\base\InvalidConfigException;
use yii\base\InvalidParamException; use yii\base\InvalidParamException;
use yii\base\UnknownClassException; use yii\base\UnknownClassException;
use yii\log\Logger; use yii\log\Logger;
use yii\di\Container;
/** /**
* Gets the application start timestamp. * Gets the application start timestamp.
...@@ -76,26 +77,13 @@ class BaseYii ...@@ -76,26 +77,13 @@ class BaseYii
*/ */
public static $aliases = ['@yii' => __DIR__]; public static $aliases = ['@yii' => __DIR__];
/** /**
* @var array initial property values that will be applied to objects newly created via [[createObject]]. * @var Container the dependency injection (DI) container used by [[createObject()]].
* The array keys are class names without leading backslashes "\", and the array values are the corresponding * You may use [[Container::set()]] to set up the needed dependencies of classes and
* name-value pairs for initializing the created class instances. For example, * their initial property values.
*
* ~~~
* [
* 'Bar' => [
* 'prop1' => 'value1',
* 'prop2' => 'value2',
* ],
* 'mycompany\foo\Car' => [
* 'prop1' => 'value1',
* 'prop2' => 'value2',
* ],
* ]
* ~~~
*
* @see createObject() * @see createObject()
* @see Container
*/ */
public static $objectConfig = []; public static $container;
/** /**
...@@ -304,11 +292,13 @@ class BaseYii ...@@ -304,11 +292,13 @@ class BaseYii
/** /**
* Creates a new object using the given configuration. * Creates a new object using the given configuration.
* *
* The configuration can be either a string or an array. * The following kinds of configuration are supported:
* If a string, it is treated as the *object class*; if an array, *
* it must contain a `class` element specifying the *object class*, and * - a string: representing the class name of the object to be created
* the rest of the name-value pairs in the array will be used to initialize * - a configuration array: the array must contain a `class` element which is treated as the object class,
* the corresponding object properties. * and the rest of the name-value pairs will be used to initialize the corresponding object properties
* - a PHP callable: either an anonymous function or an array representing a class method (`[$class or $object, $method]`).
* The callable should return a new instance of the object being created.
* *
* Below are some usage examples: * Below are some usage examples:
* *
...@@ -318,60 +308,44 @@ class BaseYii ...@@ -318,60 +308,44 @@ class BaseYii
* 'class' => 'app\components\GoogleMap', * 'class' => 'app\components\GoogleMap',
* 'apiKey' => 'xyz', * 'apiKey' => 'xyz',
* ]); * ]);
* $object = \Yii::createObject([
* return new \yii\base\Object;
* ]);
* ~~~ * ~~~
* *
* Note that the last usage is mainly useful to create an object based on some dynamic configuration
* specified as a property of a component.
*
* This method can be used to create any object as long as the object's constructor is * This method can be used to create any object as long as the object's constructor is
* defined like the following: * defined like the following:
* *
* ~~~ * ~~~
* public function __construct(..., $config = []) { * public function __construct(..., $config = [])
* {
* } * }
* ~~~ * ~~~
* *
* The method will pass the given configuration as the last parameter of the constructor, * The method will pass the given configuration as the last parameter of the constructor,
* and any additional parameters to this method will be passed as the rest of the constructor parameters. * and any additional parameters to this method will be passed as the rest of the constructor parameters.
* *
* @param string|array $config the configuration. It can be either a string representing the class name * @param string|array|callable $config the configuration for creating the object.
* or an array representing the object configuration. * @return mixed the created object
* @return mixed the created object
* @throws InvalidConfigException if the configuration is invalid. * @throws InvalidConfigException if the configuration is invalid.
*/ */
public static function createObject($config) public static function createObject($type, array $params = [])
{ {
static $reflections = []; if (is_string($type)) {
return static::$container->get($type, $params);
if (is_string($config)) { } elseif (is_array($type) && isset($type['class'])) {
$class = $config; $class = $type['class'];
$config = []; unset($type['class']);
} elseif (isset($config['class'])) { return static::$container->get($class, $params, $type);
$class = $config['class']; } elseif (is_callable($type, true)) {
unset($config['class']); return call_user_func($type, $params, static::$container);
} else { } elseif (is_array($type)) {
throw new InvalidConfigException('Object configuration must be an array containing a "class" element.'); throw new InvalidConfigException('Object configuration must be an array containing a "class" element.');
}
$class = ltrim($class, '\\');
if (isset(static::$objectConfig[$class])) {
$config = array_merge(static::$objectConfig[$class], $config);
}
if (func_num_args() > 1) {
/** @var \ReflectionClass $reflection */
if (isset($reflections[$class])) {
$reflection = $reflections[$class];
} else {
$reflection = $reflections[$class] = new \ReflectionClass($class);
}
$args = func_get_args();
array_shift($args); // remove $config
if (!empty($config)) {
$args[] = $config;
}
return $reflection->newInstanceArgs($args);
} else { } else {
return empty($config) ? new $class : new $class($config); throw new InvalidConfigException("Unsupported configuration type: " . gettype($type));
} }
} }
......
...@@ -24,3 +24,4 @@ class Yii extends \yii\BaseYii ...@@ -24,3 +24,4 @@ class Yii extends \yii\BaseYii
spl_autoload_register(['Yii', 'autoload'], true, true); spl_autoload_register(['Yii', 'autoload'], true, true);
Yii::$classMap = include(__DIR__ . '/classes.php'); Yii::$classMap = include(__DIR__ . '/classes.php');
Yii::$container = new yii\di\Container;
...@@ -192,7 +192,7 @@ class Controller extends Component implements ViewContextInterface ...@@ -192,7 +192,7 @@ class Controller extends Component implements ViewContextInterface
$actionMap = $this->actions(); $actionMap = $this->actions();
if (isset($actionMap[$id])) { if (isset($actionMap[$id])) {
return Yii::createObject($actionMap[$id], $id, $this); return Yii::createObject($actionMap[$id], [$id, $this]);
} elseif (preg_match('/^[a-z0-9\\-_]+$/', $id) && strpos($id, '--') === false && trim($id, '-') === $id) { } elseif (preg_match('/^[a-z0-9\\-_]+$/', $id) && strpos($id, '--') === false && trim($id, '-') === $id) {
$methodName = 'action' . str_replace(' ', '', ucwords(implode(' ', explode('-', $id)))); $methodName = 'action' . str_replace(' ', '', ucwords(implode(' ', explode('-', $id))));
if (method_exists($this, $methodName)) { if (method_exists($this, $methodName)) {
......
...@@ -8,8 +8,7 @@ ...@@ -8,8 +8,7 @@
namespace yii\base; namespace yii\base;
use Yii; use Yii;
use yii\di\ContainerInterface; use yii\di\ServiceLocator;
use yii\di\ContainerTrait;
/** /**
* Module is the base class for module and application classes. * Module is the base class for module and application classes.
...@@ -37,10 +36,8 @@ use yii\di\ContainerTrait; ...@@ -37,10 +36,8 @@ use yii\di\ContainerTrait;
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
*/ */
class Module extends Component implements ContainerInterface class Module extends ServiceLocator
{ {
use ContainerTrait;
/** /**
* @var array custom module parameters (name => value). * @var array custom module parameters (name => value).
*/ */
...@@ -349,7 +346,7 @@ class Module extends Component implements ContainerInterface ...@@ -349,7 +346,7 @@ class Module extends Component implements ContainerInterface
$this->_modules[$id]['class'] = 'yii\base\Module'; $this->_modules[$id]['class'] = 'yii\base\Module';
} }
return $this->_modules[$id] = Yii::createObject($this->_modules[$id], $id, $this); return $this->_modules[$id] = Yii::createObject($this->_modules[$id], [$id, $this]);
} }
} }
...@@ -522,7 +519,7 @@ class Module extends Component implements ContainerInterface ...@@ -522,7 +519,7 @@ class Module extends Component implements ContainerInterface
return $module->createController($route); return $module->createController($route);
} }
if (isset($this->controllerMap[$id])) { if (isset($this->controllerMap[$id])) {
$controller = Yii::createObject($this->controllerMap[$id], $id, $this); $controller = Yii::createObject($this->controllerMap[$id], [$id, $this]);
return [$controller, $route]; return [$controller, $route];
} }
......
...@@ -8,7 +8,7 @@ ...@@ -8,7 +8,7 @@
namespace yii\di; namespace yii\di;
/** /**
* ContainerInterface specifies the interface that a dependency injection container should implement. * ContainerInterface specifies the interface that should be implemented by a dependency inversion (DI) container.
* *
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
...@@ -16,92 +16,20 @@ namespace yii\di; ...@@ -16,92 +16,20 @@ namespace yii\di;
interface ContainerInterface interface ContainerInterface
{ {
/** /**
* Returns the list of the component definitions or the loaded shared component instances. * Returns a value indicating whether the container has the definition for the specified object type.
* @param boolean $returnDefinitions whether to return component definitions or the loaded shared component instances. * @param string $type the object type. Depending on the implementation, this could be a class name, an interface name or an alias.
* @return array the list of the component definitions or the loaded shared component instances (type or ID => definition or instance). * @return boolean whether the container has the definition for the specified object.
*/ */
public function getComponents($returnDefinitions = true); public function has($type);
/** /**
* Registers a set of component definitions in this container. * Returns an instance of the specified object type.
* *
* This is the bulk version of [[set()]]. The parameter should be an array * If the container is unable to get an instance of the object type, an exception will be thrown.
* whose keys are component types or IDs and values the corresponding component definitions. * To avoid exception, you may use [[has()]] to check if the container has the definition for
* the specified object type.
* *
* For more details on how to specify component types/IDs and definitions, please * @param string $type the object type. Depending on the implementation, this could be a class name, an interface name or an alias.
* refer to [[set()]].
*
* If a component definition with the same type/ID already exists, it will be overwritten.
*
* @param array $components component definitions or instances
*/
public function setComponents($components);
/**
* Returns a value indicating whether the container has the specified component definition or has instantiated the shared component.
* This method may return different results depending on the value of `$checkInstance`.
*
* - If `$checkInstance` is false (default), the method will return a value indicating whether the container has the specified
* component definition.
* - If `$checkInstance` is true, the method will return a value indicating whether the container has
* instantiated the specified shared component.
*
* @param string $typeOrID component type (a fully qualified namespaced class/interface name, e.g. `yii\db\Connection`) or ID (e.g. `db`).
* @param boolean $checkInstance whether the method should check if the component is shared and instantiated.
* @return boolean whether the container has the component definition of the specified type or ID
* @see set()
*/
public function has($typeOrID, $checkInstance = false);
/**
* Returns an instance of a component with the specified type or ID.
*
* If a component is registered as a shared component via [[set()]], this method will return
* the same component instance each time it is called.
* If a component is not shared, this method will create a new instance every time.
*
* @param string $typeOrID component type (a fully qualified namespaced class/interface name, e.g. `yii\db\Connection`) or ID (e.g. `db`).
* @param boolean $throwException whether to throw an exception if `$typeOrID` is not registered with the container before.
* @return object the component of the specified type or ID
* @throws \yii\base\InvalidConfigException if `$typeOrID` refers to a nonexistent component ID
* or if there is cyclic dependency detected
* @see has()
* @see set()
*/
public function get($typeOrID, $throwException = true);
/**
* Registers a component definition with this container.
*
* If a component definition with the same type/ID already exists, it will be overwritten.
*
* @param string $typeOrID component type or ID. This can be in one of the following three formats:
*
* - a fully qualified namespaced class/interface name: e.g. `yii\db\Connection`.
* This declares a shared component. Only a single instance of this class will be created and injected
* into different objects who depend on this class. If this is an interface name, the class name will
* be obtained from `$definition`.
* - a fully qualified namespaced class/interface name prefixed with an asterisk `*`: e.g. `*yii\db\Connection`.
* This declares a non-shared component. That is, if each time the container is injecting a dependency
* of this class, a new instance of this class will be created and used. If this is an interface name,
* the class name will be obtained from `$definition`.
* - an ID: e.g. `db`. This declares a shared component with an ID. The class name should
* be declared in `$definition`. When [[get()]] is called, the same component instance will be returned.
*
* @param mixed $definition the component definition to be registered with this container.
* It can be one of the followings:
*
* - a PHP callable: either an anonymous function or an array representing a class method (e.g. `['Foo', 'bar']`).
* The callable will be called by [[get()]] to return an object associated with the specified component type.
* The signature of the function should be: `function ($container)`, where `$container` is this container.
* - an object: When [[get()]] is called, this object will be returned. No new object will be created.
* This essentially makes the component a shared one, regardless how it is specified in `$typeOrID`.
* - a configuration array: the array contains name-value pairs that will be used to initialize the property
* values of the newly created object when [[get()]] is called. The `class` element stands for the
* the class of the object to be created. If `class` is not specified, `$typeOrID` will be used as the class name.
* - a string: either a class name or a component ID that is registered with this container.
*
* If the parameter is null, the component definition will be removed from the container.
*/ */
public function set($typeOrID, $definition); public function get($type);
} }
...@@ -55,10 +55,6 @@ use yii\base\InvalidConfigException; ...@@ -55,10 +55,6 @@ use yii\base\InvalidConfigException;
class Instance class Instance
{ {
/** /**
* @var ContainerInterface the container
*/
public $container;
/**
* @var string the component ID * @var string the component ID
*/ */
public $id; public $id;
...@@ -66,23 +62,20 @@ class Instance ...@@ -66,23 +62,20 @@ class Instance
/** /**
* Constructor. * Constructor.
* @param string $id the component ID * @param string $id the component ID
* @param ContainerInterface $container the container. If null, the application instance will be used.
*/ */
protected function __construct($id, ContainerInterface $container = null) protected function __construct($id)
{ {
$this->id = $id; $this->id = $id;
$this->container = $container;
} }
/** /**
* Creates a new Instance object. * Creates a new Instance object.
* @param string $id the component ID * @param string $id the component ID
* @param ContainerInterface $container the container. If null, the application instance will be used.
* @return Instance the new Instance object. * @return Instance the new Instance object.
*/ */
public static function of($id, ContainerInterface $container = null) public static function of($id)
{ {
return new static($id, $container); return new static($id);
} }
/** /**
...@@ -111,48 +104,45 @@ class Instance ...@@ -111,48 +104,45 @@ class Instance
* @return object * @return object
* @throws \yii\base\InvalidConfigException * @throws \yii\base\InvalidConfigException
*/ */
public static function ensure($value, $type, $container = null) public static function ensure($value, $type = null, $container = null)
{ {
if (empty($value)) {
throw new InvalidConfigException('The required component is not specified.');
}
if ($value instanceof $type) { if ($value instanceof $type) {
return $value; return $value;
} elseif (is_string($value)) { } elseif (empty($value)) {
$value = new static($value, $container); throw new InvalidConfigException('The required component is not specified.');
}
if (is_string($value)) {
$value = new static($value);
} }
if ($value instanceof self) { if ($value instanceof self) {
$component = $value->get(); $component = $value->get($container);
if ($component instanceof $type) { if ($component instanceof $type || $type === null) {
return $component; return $component;
} else { } else {
$container = $value->container ? : Yii::$app; throw new InvalidConfigException('"' . $value->id . '" refers to a ' . get_class($component) . " component. $type is expected.");
if ($component === null) {
throw new InvalidConfigException('"' . $value->id . '" is not a valid component ID of ' . get_class($container));
} else {
throw new InvalidConfigException('"' . $value->id . '" refers to a ' . get_class($component) . " component. $type is expected.");
}
} }
} else {
$valueType = is_object($value) ? get_class($value) : gettype($value);
throw new InvalidConfigException("Invalid data type: $valueType. $type is expected.");
} }
$valueType = is_object($value) ? get_class($value) : gettype($value);
throw new InvalidConfigException("Invalid data type: $valueType. $type is expected.");
} }
/** /**
* Returns the actual component referenced by this Instance object. * Returns the actual component referenced by this Instance object.
* @return object the actual component referenced by this Instance object. * @return object the actual component referenced by this Instance object.
* @throws InvalidConfigException there is no container available
*/ */
public function get() public function get($container = null)
{ {
/** @var ContainerInterface $container */ /** @var ContainerInterface $container */
$container = $this->container ? : Yii::$app; if ($container) {
if ($container !== null) {
return $container->get($this->id); return $container->get($this->id);
}
if (Yii::$app && Yii::$app->has($this->id)) {
return Yii::$app->get($this->id);
} else { } else {
throw new InvalidConfigException("Unable to locate a container for component \"{$this->id}\"."); return Yii::$container->get($this->id);
} }
} }
} }
<?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 Closure;
use yii\base\Component;
use yii\base\InvalidConfigException;
/**
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class ServiceLocator extends Component
{
/**
* @var array shared component instances indexed by their IDs
*/
private $_components = [];
/**
* @var array component definitions indexed by their IDs
*/
private $_definitions = [];
/**
* Returns a value indicating whether the locator has the specified component definition or has instantiated the component.
* This method may return different results depending on the value of `$checkInstance`.
*
* - If `$checkInstance` is false (default), the method will return a value indicating whether the locator has the specified
* component definition.
* - If `$checkInstance` is true, the method will return a value indicating whether the locator has
* instantiated the specified component.
*
* @param string $id component ID (e.g. `db`).
* @param boolean $checkInstance whether the method should check if the component is shared and instantiated.
* @return boolean whether the locator has the specified component definition or has instantiated the component.
* @see set()
*/
public function has($id, $checkInstance = false)
{
return $checkInstance ? isset($this->_components[$id]) : isset($this->_definitions[$id]);
}
/**
* Returns the component instance with the specified ID.
*
* @param string $id component ID (e.g. `db`).
* @param boolean $throwException whether to throw an exception if `$id` is not registered with the locator before.
* @return object|null the component of the specified ID. If `$throwException` is false and `$id`
* is not registered before, null will be returned.
* @throws InvalidConfigException if `$id` refers to a nonexistent component ID
* @see has()
* @see set()
*/
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;
}
}
/**
* Registers a component definition with this locator.
*
* For example,
*
* ```php
* // via configuration array
* $locator->set('db', [
* 'class' => 'yii\db\Connection',
* 'dsn' => '...',
* ]);
*
* // via anonymous function
* $locator->set('db', function ($locator) {
* return new \yii\db\Connection;
* });
* ```
*
* If a component definition with the same ID already exists, it will be overwritten.
*
* If `$definition` is null, the previously registered component definition will be removed.
*
* @param string $id component ID (e.g. `db`).
* @param mixed $definition the component definition to be registered with this locator.
* It can be one of the followings:
*
* - a PHP callable: either an anonymous function or an array representing a class method (e.g. `['Foo', 'bar']`).
* The callable will be called by [[get()]] to return an object associated with the specified component ID.
* The signature of the function should be: `function ($locator)`, where `$locator` is this locator.
* - an object: When [[get()]] is called, this object will be returned.
* - a configuration array or a class name: the array contains name-value pairs that will be used to
* initialize the property values of the newly created object when [[get()]] is called.
* The `class` element stands for the the class of the object to be created.
*
* @throws InvalidConfigException if the definition is an invalid configuration array
*/
public function set($id, $definition)
{
if ($definition === null) {
unset($this->_components[$id], $this->_definitions[$id]);
return;
}
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));
}
}
/**
* Returns the list of the component definitions or the loaded component instances.
* @param boolean $returnDefinitions whether to return component definitions or the loaded component instances.
* @return array the list of the component definitions or the loaded component instances (ID => definition or instance).
*/
public function getComponents($returnDefinitions = true)
{
return $returnDefinitions ? $this->_definitions : $this->_components;
}
/**
* Registers a set of component definitions in this locator.
*
* This is the bulk version of [[set()]]. The parameter should be an array
* whose keys are component IDs and values the corresponding component definitions.
*
* For more details on how to specify component IDs and definitions, please refer to [[set()]].
*
* If a component definition with the same ID already exists, it will be overwritten.
*
* The following is an example for registering two component definitions:
*
* ~~~
* [
* 'db' => [
* 'class' => 'yii\db\Connection',
* 'dsn' => 'sqlite:path/to/file.db',
* ],
* 'cache' => [
* 'class' => 'yii\caching\DbCache',
* 'db' => 'db',
* ],
* ]
* ~~~
*
* @param array $components component definitions or instances
*/
public function setComponents($components)
{
foreach ($components as $id => $component) {
$this->set($id, $component);
}
}
}
<?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 Closure;
use yii\base\InvalidConfigException;
/**
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
trait ServiceLocatorTrait
{
/**
* @var array shared component instances indexed by their IDs
*/
private $_components = [];
/**
* @var array component definitions indexed by their IDs
*/
private $_definitions = [];
/**
* Returns a value indicating whether the locator has the specified component definition or has instantiated the component.
* This method may return different results depending on the value of `$checkInstance`.
*
* - If `$checkInstance` is false (default), the method will return a value indicating whether the locator has the specified
* component definition.
* - If `$checkInstance` is true, the method will return a value indicating whether the locator has
* instantiated the specified component.
*
* @param string $id component ID (e.g. `db`).
* @param boolean $checkInstance whether the method should check if the component is shared and instantiated.
* @return boolean whether the locator has the specified component definition or has instantiated the component.
* @see set()
*/
public function has($id, $checkInstance = false)
{
return $checkInstance ? isset($this->_components[$id]) : isset($this->_definitions[$id]);
}
/**
* Returns the component instance with the specified ID.
*
* @param string $id component ID (e.g. `db`).
* @param boolean $throwException whether to throw an exception if `$id` is not registered with the locator before.
* @return object|null the component of the specified ID. If `$throwException` is false and `$id`
* is not registered before, null will be returned.
* @throws InvalidConfigException if `$id` refers to a nonexistent component ID
* @see has()
* @see set()
*/
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;
}
}
/**
* Registers a component definition with this locator.
*
* For example,
*
* ```php
* // via configuration array
* $locator->set('db', [
* 'class' => 'yii\db\Connection',
* 'dsn' => '...',
* ]);
*
* // via anonymous function
* $locator->set('db', function ($locator) {
* return new \yii\db\Connection;
* });
* ```
*
* If a component definition with the same ID already exists, it will be overwritten.
*
* If `$definition` is null, the previously registered component definition will be removed.
*
* @param string $id component ID (e.g. `db`).
* @param mixed $definition the component definition to be registered with this locator.
* It can be one of the followings:
*
* - a PHP callable: either an anonymous function or an array representing a class method (e.g. `['Foo', 'bar']`).
* The callable will be called by [[get()]] to return an object associated with the specified component ID.
* The signature of the function should be: `function ($locator)`, where `$locator` is this locator.
* - an object: When [[get()]] is called, this object will be returned.
* - a configuration array or a class name: the array contains name-value pairs that will be used to
* initialize the property values of the newly created object when [[get()]] is called.
* The `class` element stands for the the class of the object to be created.
*
* @throws InvalidConfigException if the definition is an invalid configuration array
*/
public function set($id, $definition)
{
if ($definition === null) {
unset($this->_components[$id], $this->_definitions[$id]);
return;
}
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));
}
}
/**
* Returns the list of the component definitions or the loaded component instances.
* @param boolean $returnDefinitions whether to return component definitions or the loaded component instances.
* @return array the list of the component definitions or the loaded component instances (ID => definition or instance).
*/
public function getComponents($returnDefinitions = true)
{
return $returnDefinitions ? $this->_definitions : $this->_components;
}
/**
* Registers a set of component definitions in this locator.
*
* This is the bulk version of [[set()]]. The parameter should be an array
* whose keys are component IDs and values the corresponding component definitions.
*
* For more details on how to specify component IDs and definitions, please refer to [[set()]].
*
* If a component definition with the same ID already exists, it will be overwritten.
*
* The following is an example for registering two component definitions:
*
* ~~~
* [
* 'db' => [
* 'class' => 'yii\db\Connection',
* 'dsn' => 'sqlite:path/to/file.db',
* ],
* 'cache' => [
* 'class' => 'yii\caching\DbCache',
* 'db' => 'db',
* ],
* ]
* ~~~
*
* @param array $components component definitions or instances
*/
public function setComponents($components)
{
foreach ($components as $id => $component) {
$this->set($id, $component);
}
}
}
...@@ -7,24 +7,13 @@ ...@@ -7,24 +7,13 @@
namespace yiiunit\framework\di; namespace yiiunit\framework\di;
use yii\base\Object;
use yii\di\Container; use yii\di\Container;
use yii\di\Instance;
use yiiunit\framework\di\stubs\Bar;
use yiiunit\framework\di\stubs\Foo;
use yiiunit\framework\di\stubs\Qux;
use yiiunit\TestCase; use yiiunit\TestCase;
class Creator
{
public static function create($type, $container)
{
return new $type;
}
}
class TestClass extends Object
{
public $prop1 = 1;
public $prop2;
}
/** /**
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
...@@ -34,118 +23,62 @@ class ContainerTest extends TestCase ...@@ -34,118 +23,62 @@ class ContainerTest extends TestCase
{ {
public function testDefault() public function testDefault()
{ {
// without configuring anything $namespace = __NAMESPACE__ . '\stubs';
$container = new Container; $QuxInterface = "$namespace\\QuxInterface";
$className = TestClass::className(); $Foo = Foo::className();
$object = $container->get($className); $Bar = Bar::className();
$this->assertEquals(1, $object->prop1); $Qux = Qux::className();
$this->assertTrue($object instanceof $className);
// check non-shared
$object2 = $container->get($className);
$this->assertTrue($object2 instanceof $className);
$this->assertTrue($object !== $object2);
}
public function testCallable()
{
// anonymous function
$container = new Container;
$className = TestClass::className();
$container->set($className, function ($type) {
return new $type([
'prop1' => 100,
'prop2' => 200,
]);
});
$object = $container->get($className);
$this->assertTrue($object instanceof $className);
$this->assertEquals(100, $object->prop1);
$this->assertEquals(200, $object->prop2);
// static method
$container = new Container;
$className = TestClass::className();
$container->set($className, [__NAMESPACE__ . "\\Creator", 'create']);
$object = $container->get($className);
$this->assertTrue($object instanceof $className);
$this->assertEquals(1, $object->prop1);
$this->assertNull($object->prop2);
}
public function testObject()
{
$object = new TestClass;
$className = TestClass::className();
$container = new Container;
$container->set($className, $object);
$this->assertTrue($container->get($className) === $object);
}
public function testString() // automatic wiring
{
$object = new TestClass;
$className = TestClass::className();
$container = new Container; $container = new Container;
$container->set('test', $object); $container->set($QuxInterface, $Qux);
$container->set($className, 'test'); $foo = $container->get($Foo);
$this->assertTrue($container->get($className) === $object); $this->assertTrue($foo instanceof $Foo);
} $this->assertTrue($foo->bar instanceof $Bar);
$this->assertTrue($foo->bar->qux instanceof $Qux);
public function testShared() // full wiring
{
// with configuration: shared
$container = new Container; $container = new Container;
$className = TestClass::className(); $container->set($QuxInterface, $Qux);
$container->set($className, [ $container->set($Bar);
'prop1' => 10, $container->set($Qux);
'prop2' => 20, $container->set($Foo);
]); $foo = $container->get($Foo);
$object = $container->get($className); $this->assertTrue($foo instanceof $Foo);
$this->assertEquals(10, $object->prop1); $this->assertTrue($foo->bar instanceof $Bar);
$this->assertEquals(20, $object->prop2); $this->assertTrue($foo->bar->qux instanceof $Qux);
$this->assertTrue($object instanceof $className);
// check shared
$object2 = $container->get($className);
$this->assertTrue($object2 instanceof $className);
$this->assertTrue($object === $object2);
}
public function testNonShared() // wiring by closure
{
// with configuration: non-shared
$container = new Container; $container = new Container;
$className = TestClass::className(); $container->set('foo', function () {
$container->set('*' . $className, [ $qux = new Qux;
'prop1' => 10, $bar = new Bar($qux);
'prop2' => 20, return new Foo($bar);
]); });
$object = $container->get($className); $foo = $container->get('foo');
$this->assertEquals(10, $object->prop1); $this->assertTrue($foo instanceof $Foo);
$this->assertEquals(20, $object->prop2); $this->assertTrue($foo->bar instanceof $Bar);
$this->assertTrue($object instanceof $className); $this->assertTrue($foo->bar->qux instanceof $Qux);
// check non-shared
$object2 = $container->get($className);
$this->assertTrue($object2 instanceof $className);
$this->assertTrue($object !== $object2);
// shared as non-shared // wiring by closure which uses container
$object = new TestClass;
$className = TestClass::className();
$container = new Container; $container = new Container;
$container->set('*' . $className, $object); $container->set($QuxInterface, $Qux);
$this->assertTrue($container->get($className) === $object); $container->set('foo', function ($params, $config, Container $c) {
} return $c->get(Foo::className());
});
$foo = $container->get('foo');
$this->assertTrue($foo instanceof $Foo);
$this->assertTrue($foo->bar instanceof $Bar);
$this->assertTrue($foo->bar->qux instanceof $Qux);
public function testRegisterByID() // predefined constructor parameters
{
$className = TestClass::className();
$container = new Container; $container = new Container;
$container->set('test', [ $container->set('foo', $Foo, [Instance::of('bar')]);
'class' => $className, $container->set('bar', $Bar, [Instance::of('qux')]);
'prop1' => 100, $container->set('qux', $Qux);
]); $foo = $container->get('foo');
$object = $container->get('test'); $this->assertTrue($foo instanceof $Foo);
$this->assertTrue($object instanceof TestClass); $this->assertTrue($foo->bar instanceof $Bar);
$this->assertEquals(100, $object->prop1); $this->assertTrue($foo->bar->qux instanceof $Qux);
} }
} }
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yiiunit\framework\di;
use yii\base\Object;
use yii\di\Container;
use yiiunit\TestCase;
class Creator
{
public static function create($type, $container)
{
return new $type;
}
}
class TestClass extends Object
{
public $prop1 = 1;
public $prop2;
}
/**
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class ServiceLocatorTest extends TestCase
{
public function testDefault()
{
// without configuring anything
$container = new Container;
$className = TestClass::className();
$object = $container->get($className);
$this->assertEquals(1, $object->prop1);
$this->assertTrue($object instanceof $className);
// check non-shared
$object2 = $container->get($className);
$this->assertTrue($object2 instanceof $className);
$this->assertTrue($object !== $object2);
}
public function testCallable()
{
// anonymous function
$container = new Container;
$className = TestClass::className();
$container->set($className, function ($type) {
return new $type([
'prop1' => 100,
'prop2' => 200,
]);
});
$object = $container->get($className);
$this->assertTrue($object instanceof $className);
$this->assertEquals(100, $object->prop1);
$this->assertEquals(200, $object->prop2);
// static method
$container = new Container;
$className = TestClass::className();
$container->set($className, [__NAMESPACE__ . "\\Creator", 'create']);
$object = $container->get($className);
$this->assertTrue($object instanceof $className);
$this->assertEquals(1, $object->prop1);
$this->assertNull($object->prop2);
}
public function testObject()
{
$object = new TestClass;
$className = TestClass::className();
$container = new Container;
$container->set($className, $object);
$this->assertTrue($container->get($className) === $object);
}
public function testString()
{
$object = new TestClass;
$className = TestClass::className();
$container = new Container;
$container->set('test', $object);
$container->set($className, 'test');
$this->assertTrue($container->get($className) === $object);
}
public function testShared()
{
// with configuration: shared
$container = new Container;
$className = TestClass::className();
$container->set($className, [
'prop1' => 10,
'prop2' => 20,
]);
$object = $container->get($className);
$this->assertEquals(10, $object->prop1);
$this->assertEquals(20, $object->prop2);
$this->assertTrue($object instanceof $className);
// check shared
$object2 = $container->get($className);
$this->assertTrue($object2 instanceof $className);
$this->assertTrue($object === $object2);
}
public function testNonShared()
{
// with configuration: non-shared
$container = new Container;
$className = TestClass::className();
$container->set('*' . $className, [
'prop1' => 10,
'prop2' => 20,
]);
$object = $container->get($className);
$this->assertEquals(10, $object->prop1);
$this->assertEquals(20, $object->prop2);
$this->assertTrue($object instanceof $className);
// check non-shared
$object2 = $container->get($className);
$this->assertTrue($object2 instanceof $className);
$this->assertTrue($object !== $object2);
// shared as non-shared
$object = new TestClass;
$className = TestClass::className();
$container = new Container;
$container->set('*' . $className, $object);
$this->assertTrue($container->get($className) === $object);
}
public function testRegisterByID()
{
$className = TestClass::className();
$container = new Container;
$container->set('test', [
'class' => $className,
'prop1' => 100,
]);
$object = $container->get('test');
$this->assertTrue($object instanceof TestClass);
$this->assertEquals(100, $object->prop1);
}
}
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yiiunit\framework\di\stubs;
use yii\base\Object;
/**
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class Bar extends Object
{
public $qux;
public function __construct(QuxInterface $qux, $config = [])
{
$this->qux = $qux;
parent::__construct($config);
}
}
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yiiunit\framework\di\stubs;
use yii\base\Object;
/**
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class Foo extends Object
{
public $bar;
public function __construct(Bar $bar, $config = [])
{
$this->bar = $bar;
parent::__construct($config);
}
}
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yiiunit\framework\di\stubs;
use yii\base\Object;
/**
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class Qux extends Object implements QuxInterface
{
public $a;
public function __construct($a = 1, $config = [])
{
$this->a = $a;
parent::__construct($config);
}
public function quxMethod()
{
}
}
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yiiunit\framework\di\stubs;
/**
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
interface QuxInterface
{
function quxMethod();
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment