Yii2 framework backup
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

265 lines
9.2 KiB

11 years ago
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\di;
use Closure;
Added php-cs-fixer coding standards validation to Travis CI (#14100) * php-cs-fixer: PSR2 rule. * php-cs-fixer: PSR2 rule - fix views. * Travis setup refactoring. * Add php-cs-fixer to travis cs tests. * Fix tests on hhvm-3.12 * improve travis config * composer update * revert composer update * improve travis config * Fix CS. * Extract config to separate classes. * Extract config to separate classes. * Add file header. * Force short array syntax. * binary_operator_spaces fixer * Fix broken tests * cast_spaces fixer * concat_space fixer * dir_constant fixer * ereg_to_preg fixer * function_typehint_space fixer * hash_to_slash_comment fixer * is_null fixer * linebreak_after_opening_tag fixer * lowercase_cast fixer * magic_constant_casing fixer * modernize_types_casting fixer * native_function_casing fixer * new_with_braces fixer * no_alias_functions fixer * no_blank_lines_after_class_opening fixer * no_blank_lines_after_phpdoc fixer * no_empty_comment fixer * no_empty_phpdoc fixer * no_empty_statement fixer * no_extra_consecutive_blank_lines fixer * no_leading_import_slash fixer * no_leading_namespace_whitespace fixer * no_mixed_echo_print fixer * no_multiline_whitespace_around_double_arrow fixer * no_multiline_whitespace_before_semicolons fixer * no_php4_constructor fixer * no_short_bool_cast fixer * no_singleline_whitespace_before_semicolons fixer * no_spaces_around_offset fixer * no_trailing_comma_in_list_call fixer * no_trailing_comma_in_singleline_array fixer * no_unneeded_control_parentheses fixer * no_unused_imports fixer * no_useless_return fixer * no_whitespace_before_comma_in_array fixer * no_whitespace_in_blank_line fixer * not_operator_with_successor_space fixer * object_operator_without_whitespace fixer * ordered_imports fixer * php_unit_construct fixer * php_unit_dedicate_assert fixer * php_unit_fqcn_annotation fixer * phpdoc_indent fixer * phpdoc_no_access fixer * phpdoc_no_empty_return fixer * phpdoc_no_package fixer * phpdoc_no_useless_inheritdoc fixer * Fix broken tests * phpdoc_return_self_reference fixer * phpdoc_single_line_var_spacing fixer * phpdoc_single_line_var_spacing fixer * phpdoc_to_comment fixer * phpdoc_trim fixer * phpdoc_var_without_name fixer * psr4 fixer * self_accessor fixer * short_scalar_cast fixer * single_blank_line_before_namespace fixer * single_quote fixer * standardize_not_equals fixer * ternary_operator_spaces fixer * trailing_comma_in_multiline_array fixer * trim_array_spaces fixer * protected_to_private fixer * unary_operator_spaces fixer * whitespace_after_comma_in_array fixer * `parent::setRules()` -> `$this->setRules()` * blank_line_after_opening_tag fixer * Update finder config. * Revert changes for YiiRequirementChecker. * Fix array formatting. * Add missing import. * Fix CS for new code merged from master. * Fix some indentation issues.
7 years ago
use Yii;
11 years ago
use yii\base\Component;
use yii\base\InvalidConfigException;
/**
* ServiceLocator implements a [service locator](http://en.wikipedia.org/wiki/Service_locator_pattern).
*
* To use ServiceLocator, you first need to register component IDs with the corresponding component
* definitions with the locator by calling [[set()]] or [[setComponents()]].
* You can then call [[get()]] to retrieve a component with the specified ID. The locator will automatically
* instantiate and configure the component according to the definition.
*
* For example,
*
* ```php
* $locator = new \yii\di\ServiceLocator;
* $locator->setComponents([
* 'db' => [
* 'class' => 'yii\db\Connection',
* 'dsn' => 'sqlite:path/to/file.db',
* ],
* 'cache' => [
* 'class' => 'yii\caching\DbCache',
* 'db' => 'db',
* ],
* ]);
*
11 years ago
* $db = $locator->get('db'); // or $locator->db
* $cache = $locator->get('cache'); // or $locator->cache
* ```
*
* Because [[\yii\base\Module]] extends from ServiceLocator, modules and the application are all service locators.
* Modules add [tree traversal](guide:concept-service-locator#tree-traversal) for service resolution.
11 years ago
*
* For more details and usage information on ServiceLocator, see the [guide article on service locators](guide:concept-service-locator).
*
* @property array $components The list of the component definitions or the loaded component instances (ID =>
* definition or instance).
*
11 years ago
* @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 = [];
11 years ago
/**
11 years ago
* Getter magic method.
* This method is overridden to support accessing components like reading properties.
* @param string $name component or property name
* @return mixed the named property value
11 years ago
*/
public function __get($name)
{
if ($this->has($name)) {
return $this->get($name);
}
return parent::__get($name);
11 years ago
}
/**
* Checks if a property value is null.
* This method overrides the parent implementation by checking if the named component is loaded.
* @param string $name the property name or the event name
* @return bool whether the property value is null
11 years ago
*/
public function __isset($name)
{
if ($this->has($name)) {
11 years ago
return true;
}
return parent::__isset($name);
11 years ago
}
/**
11 years ago
* 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 bool $checkInstance whether the method should check if the component is shared and instantiated.
* @return bool whether the locator has the specified component definition or has instantiated the component.
11 years ago
* @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 bool $throwException whether to throw an exception if `$id` is not registered with the locator before.
11 years ago
* @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;
}
return $this->_components[$id] = Yii::createObject($definition);
11 years ago
} elseif ($throwException) {
throw new InvalidConfigException("Unknown component ID: $id");
}
return null;
11 years ago
}
/**
* Registers a component definition with this locator.
*
* For example,
*
* ```php
* // a class name
* $locator->set('cache', 'yii\caching\FileCache');
*
* // a configuration array
11 years ago
* $locator->set('db', [
* 'class' => 'yii\db\Connection',
* 'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
* 'username' => 'root',
* 'password' => '',
* 'charset' => 'utf8',
11 years ago
* ]);
*
* // an anonymous function
* $locator->set('cache', function ($params) {
* return new \yii\caching\FileCache;
11 years ago
* });
*
* // an instance
* $locator->set('cache', new \yii\caching\FileCache);
11 years ago
* ```
*
* If a component definition with the same ID already exists, it will be overwritten.
*
* @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 following:
11 years ago
*
* - a class name
* - 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 is required and stands for the the class of the object to be created.
11 years ago
* - 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.
* - an object: When [[get()]] is called, this object will be returned.
*
* @throws InvalidConfigException if the definition is an invalid configuration array
*/
public function set($id, $definition)
{
unset($this->_components[$id]);
11 years ago
if ($definition === null) {
unset($this->_definitions[$id]);
11 years ago
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));
}
}
/**
* Removes the component from the locator.
* @param string $id the component ID
*/
public function clear($id)
{
unset($this->_definitions[$id], $this->_components[$id]);
}
/**
11 years ago
* Returns the list of the component definitions or the loaded component instances.
* @param bool $returnDefinitions whether to return component definitions instead of the loaded component instances.
11 years ago
* @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:
*
* ```php
11 years ago
* [
* 'db' => [
* 'class' => 'yii\db\Connection',
* 'dsn' => 'sqlite:path/to/file.db',
* ],
* 'cache' => [
* 'class' => 'yii\caching\DbCache',
* 'db' => 'db',
* ],
* ]
* ```
11 years ago
*
* @param array $components component definitions or instances
*/
public function setComponents($components)
{
foreach ($components as $id => $component) {
$this->set($id, $component);
}
}
}