Commit 8c2e3923 by Qiang Xue

Turn module and application into DI containers.

parent 66abd5b8
...@@ -164,7 +164,7 @@ class AuthAction extends Action ...@@ -164,7 +164,7 @@ class AuthAction extends Action
if (!empty($_GET[$this->clientIdGetParamName])) { if (!empty($_GET[$this->clientIdGetParamName])) {
$clientId = $_GET[$this->clientIdGetParamName]; $clientId = $_GET[$this->clientIdGetParamName];
/** @var \yii\authclient\Collection $collection */ /** @var \yii\authclient\Collection $collection */
$collection = Yii::$app->getComponent($this->clientCollection); $collection = Yii::$app->get($this->clientCollection);
if (!$collection->hasClient($clientId)) { if (!$collection->hasClient($clientId)) {
throw new NotFoundHttpException("Unknown auth client '{$clientId}'"); throw new NotFoundHttpException("Unknown auth client '{$clientId}'");
} }
......
...@@ -143,7 +143,7 @@ class Choice extends Widget ...@@ -143,7 +143,7 @@ class Choice extends Widget
protected function defaultClients() protected function defaultClients()
{ {
/** @var $collection \yii\authclient\Collection */ /** @var $collection \yii\authclient\Collection */
$collection = Yii::$app->getComponent($this->clientCollection); $collection = Yii::$app->get($this->clientCollection);
return $collection->getClients(); return $collection->getClients();
} }
......
...@@ -86,7 +86,7 @@ class RequestPanel extends Panel ...@@ -86,7 +86,7 @@ class RequestPanel extends Panel
$action = null; $action = null;
} }
/** @var \yii\web\Session $session */ /** @var \yii\web\Session $session */
$session = Yii::$app->getComponent('session', false); $session = Yii::$app->get('session', [], false);
return [ return [
'flashes' => $session ? $session->getAllFlashes() : [], 'flashes' => $session ? $session->getAllFlashes() : [],
......
...@@ -59,7 +59,7 @@ class ActiveRecord extends BaseActiveRecord ...@@ -59,7 +59,7 @@ class ActiveRecord extends BaseActiveRecord
*/ */
public static function getDb() public static function getDb()
{ {
return \Yii::$app->getComponent('elasticsearch'); return \Yii::$app->get('elasticsearch');
} }
/** /**
......
...@@ -55,7 +55,7 @@ class DebugAction extends Action ...@@ -55,7 +55,7 @@ class DebugAction extends Action
$options = ['pretty' => true]; $options = ['pretty' => true];
/** @var Connection $db */ /** @var Connection $db */
$db = \Yii::$app->getComponent($this->db); $db = \Yii::$app->get($this->db);
$time = microtime(true); $time = microtime(true);
switch ($method) { switch ($method) {
case 'GET': $result = $db->get($url, $options, $body, true); break; case 'GET': $result = $db->get($url, $options, $body, true); break;
......
...@@ -115,7 +115,7 @@ class Query extends Component implements QueryInterface ...@@ -115,7 +115,7 @@ class Query extends Component implements QueryInterface
public function createCommand($db = null) public function createCommand($db = null)
{ {
if ($db === null) { if ($db === null) {
$db = Yii::$app->getComponent('elasticsearch'); $db = Yii::$app->get('elasticsearch');
} }
$commandConfig = $db->getQueryBuilder()->build($this); $commandConfig = $db->getQueryBuilder()->build($this);
......
...@@ -439,7 +439,7 @@ class Generator extends \yii\gii\Generator ...@@ -439,7 +439,7 @@ class Generator extends \yii\gii\Generator
{ {
if (Yii::$app->hasComponent($this->db) === false) { if (Yii::$app->hasComponent($this->db) === false) {
$this->addError('db', 'There is no application component named "db".'); $this->addError('db', 'There is no application component named "db".');
} elseif (!Yii::$app->getComponent($this->db) instanceof Connection) { } elseif (!Yii::$app->get($this->db) instanceof Connection) {
$this->addError('db', 'The "db" application component must be a DB connection instance.'); $this->addError('db', 'The "db" application component must be a DB connection instance.');
} }
} }
......
...@@ -29,7 +29,7 @@ abstract class ActiveRecord extends BaseActiveRecord ...@@ -29,7 +29,7 @@ abstract class ActiveRecord extends BaseActiveRecord
*/ */
public static function getDb() public static function getDb()
{ {
return \Yii::$app->getComponent('mongodb'); return \Yii::$app->get('mongodb');
} }
/** /**
......
...@@ -62,7 +62,7 @@ class Cache extends \yii\caching\Cache ...@@ -62,7 +62,7 @@ class Cache extends \yii\caching\Cache
{ {
parent::init(); parent::init();
if (is_string($this->db)) { if (is_string($this->db)) {
$this->db = Yii::$app->getComponent($this->db); $this->db = Yii::$app->get($this->db);
} }
if (!$this->db instanceof Connection) { if (!$this->db instanceof Connection) {
throw new InvalidConfigException($this->className() . "::db must be either a MongoDB connection instance or the application component ID of a MongoDB connection."); throw new InvalidConfigException($this->className() . "::db must be either a MongoDB connection instance or the application component ID of a MongoDB connection.");
......
...@@ -62,7 +62,7 @@ class Query extends Component implements QueryInterface ...@@ -62,7 +62,7 @@ class Query extends Component implements QueryInterface
public function getCollection($db = null) public function getCollection($db = null)
{ {
if ($db === null) { if ($db === null) {
$db = Yii::$app->getComponent('mongodb'); $db = Yii::$app->get('mongodb');
} }
return $db->getCollection($this->from); return $db->getCollection($this->from);
......
...@@ -56,7 +56,7 @@ class Session extends \yii\web\Session ...@@ -56,7 +56,7 @@ class Session extends \yii\web\Session
public function init() public function init()
{ {
if (is_string($this->db)) { if (is_string($this->db)) {
$this->db = Yii::$app->getComponent($this->db); $this->db = Yii::$app->get($this->db);
} }
if (!$this->db instanceof Connection) { if (!$this->db instanceof Connection) {
throw new InvalidConfigException($this->className() . "::db must be either a MongoDB connection instance or the application component ID of a MongoDB connection."); throw new InvalidConfigException($this->className() . "::db must be either a MongoDB connection instance or the application component ID of a MongoDB connection.");
......
...@@ -31,7 +31,7 @@ class Query extends \yii\mongodb\Query ...@@ -31,7 +31,7 @@ class Query extends \yii\mongodb\Query
public function getCollection($db = null) public function getCollection($db = null)
{ {
if ($db === null) { if ($db === null) {
$db = Yii::$app->getComponent('mongodb'); $db = Yii::$app->get('mongodb');
} }
return $db->getFileCollection($this->from); return $db->getFileCollection($this->from);
......
...@@ -45,7 +45,7 @@ class ActiveRecord extends BaseActiveRecord ...@@ -45,7 +45,7 @@ class ActiveRecord extends BaseActiveRecord
*/ */
public static function getDb() public static function getDb()
{ {
return \Yii::$app->getComponent('redis'); return \Yii::$app->get('redis');
} }
/** /**
......
...@@ -76,7 +76,7 @@ class Cache extends \yii\caching\Cache ...@@ -76,7 +76,7 @@ class Cache extends \yii\caching\Cache
{ {
parent::init(); parent::init();
if (is_string($this->redis)) { if (is_string($this->redis)) {
$this->redis = Yii::$app->getComponent($this->redis); $this->redis = Yii::$app->get($this->redis);
} elseif (is_array($this->redis)) { } elseif (is_array($this->redis)) {
if (!isset($this->redis['class'])) { if (!isset($this->redis['class'])) {
$this->redis['class'] = Connection::className(); $this->redis['class'] = Connection::className();
......
...@@ -80,7 +80,7 @@ class Session extends \yii\web\Session ...@@ -80,7 +80,7 @@ class Session extends \yii\web\Session
public function init() public function init()
{ {
if (is_string($this->redis)) { if (is_string($this->redis)) {
$this->redis = Yii::$app->getComponent($this->redis); $this->redis = Yii::$app->get($this->redis);
} elseif (is_array($this->redis)) { } elseif (is_array($this->redis)) {
if (!isset($this->redis['class'])) { if (!isset($this->redis['class'])) {
$this->redis['class'] = Connection::className(); $this->redis['class'] = Connection::className();
......
...@@ -62,7 +62,7 @@ abstract class ActiveRecord extends BaseActiveRecord ...@@ -62,7 +62,7 @@ abstract class ActiveRecord extends BaseActiveRecord
*/ */
public static function getDb() public static function getDb()
{ {
return \Yii::$app->getComponent('sphinx'); return \Yii::$app->get('sphinx');
} }
/** /**
......
...@@ -155,7 +155,7 @@ class Query extends Component implements QueryInterface ...@@ -155,7 +155,7 @@ class Query extends Component implements QueryInterface
*/ */
protected function defaultConnection() protected function defaultConnection()
{ {
return Yii::$app->getComponent('sphinx'); return Yii::$app->get('sphinx');
} }
/** /**
......
...@@ -132,7 +132,7 @@ class Schema extends Object ...@@ -132,7 +132,7 @@ class Schema extends Object
if ($db->enableSchemaCache && !in_array($name, $db->schemaCacheExclude, true)) { if ($db->enableSchemaCache && !in_array($name, $db->schemaCacheExclude, true)) {
/** @var $cache Cache */ /** @var $cache Cache */
$cache = is_string($db->schemaCache) ? Yii::$app->getComponent($db->schemaCache) : $db->schemaCache; $cache = is_string($db->schemaCache) ? Yii::$app->get($db->schemaCache) : $db->schemaCache;
if ($cache instanceof Cache) { if ($cache instanceof Cache) {
$key = $this->getCacheKey($name); $key = $this->getCacheKey($name);
if ($refresh || ($index = $cache->get($key)) === false) { if ($refresh || ($index = $cache->get($key)) === false) {
...@@ -296,7 +296,7 @@ class Schema extends Object ...@@ -296,7 +296,7 @@ class Schema extends Object
public function refresh() public function refresh()
{ {
/** @var $cache Cache */ /** @var $cache Cache */
$cache = is_string($this->db->schemaCache) ? Yii::$app->getComponent($this->db->schemaCache) : $this->db->schemaCache; $cache = is_string($this->db->schemaCache) ? Yii::$app->get($this->db->schemaCache) : $this->db->schemaCache;
if ($this->db->enableSchemaCache && $cache instanceof Cache) { if ($this->db->enableSchemaCache && $cache instanceof Cache) {
GroupDependency::invalidate($cache, $this->getCacheGroup()); GroupDependency::invalidate($cache, $this->getCacheGroup());
} }
......
...@@ -160,7 +160,6 @@ abstract class Application extends Module ...@@ -160,7 +160,6 @@ abstract class Application extends Module
$this->preInit($config); $this->preInit($config);
$this->registerErrorHandlers(); $this->registerErrorHandlers();
$this->registerCoreComponents();
Component::__construct($config); Component::__construct($config);
} }
...@@ -206,6 +205,17 @@ abstract class Application extends Module ...@@ -206,6 +205,17 @@ abstract class Application extends Module
} elseif (!ini_get('date.timezone')) { } elseif (!ini_get('date.timezone')) {
$this->setTimeZone('UTC'); $this->setTimeZone('UTC');
} }
// merge core components with custom components
if (!empty($config['components'])) {
foreach ($this->coreComponents() as $id => $component) {
if (!isset($config['components'][$id])) {
$config['components'][$id] = $component;
} elseif (!isset($config['components'][$id]['class'])) {
$config['components'][$id]['class'] = $component['class'];
}
}
}
} }
/** /**
...@@ -248,7 +258,7 @@ abstract class Application extends Module ...@@ -248,7 +258,7 @@ abstract class Application extends Module
*/ */
public function preloadComponents() public function preloadComponents()
{ {
$this->getComponent('log'); $this->get('log');
parent::preloadComponents(); parent::preloadComponents();
} }
...@@ -400,7 +410,7 @@ abstract class Application extends Module ...@@ -400,7 +410,7 @@ abstract class Application extends Module
*/ */
public function getDb() public function getDb()
{ {
return $this->getComponent('db'); return $this->get('db');
} }
/** /**
...@@ -409,7 +419,7 @@ abstract class Application extends Module ...@@ -409,7 +419,7 @@ abstract class Application extends Module
*/ */
public function getLog() public function getLog()
{ {
return $this->getComponent('log'); return $this->get('log');
} }
/** /**
...@@ -418,7 +428,7 @@ abstract class Application extends Module ...@@ -418,7 +428,7 @@ abstract class Application extends Module
*/ */
public function getErrorHandler() public function getErrorHandler()
{ {
return $this->getComponent('errorHandler'); return $this->get('errorHandler');
} }
/** /**
...@@ -427,7 +437,7 @@ abstract class Application extends Module ...@@ -427,7 +437,7 @@ abstract class Application extends Module
*/ */
public function getCache() public function getCache()
{ {
return $this->getComponent('cache'); return $this->get('cache');
} }
/** /**
...@@ -436,7 +446,7 @@ abstract class Application extends Module ...@@ -436,7 +446,7 @@ abstract class Application extends Module
*/ */
public function getFormatter() public function getFormatter()
{ {
return $this->getComponent('formatter'); return $this->get('formatter');
} }
/** /**
...@@ -445,7 +455,7 @@ abstract class Application extends Module ...@@ -445,7 +455,7 @@ abstract class Application extends Module
*/ */
public function getRequest() public function getRequest()
{ {
return $this->getComponent('request'); return $this->get('request');
} }
/** /**
...@@ -454,7 +464,7 @@ abstract class Application extends Module ...@@ -454,7 +464,7 @@ abstract class Application extends Module
*/ */
public function getView() public function getView()
{ {
return $this->getComponent('view'); return $this->get('view');
} }
/** /**
...@@ -463,7 +473,7 @@ abstract class Application extends Module ...@@ -463,7 +473,7 @@ abstract class Application extends Module
*/ */
public function getUrlManager() public function getUrlManager()
{ {
return $this->getComponent('urlManager'); return $this->get('urlManager');
} }
/** /**
...@@ -472,7 +482,7 @@ abstract class Application extends Module ...@@ -472,7 +482,7 @@ abstract class Application extends Module
*/ */
public function getI18n() public function getI18n()
{ {
return $this->getComponent('i18n'); return $this->get('i18n');
} }
/** /**
...@@ -481,7 +491,7 @@ abstract class Application extends Module ...@@ -481,7 +491,7 @@ abstract class Application extends Module
*/ */
public function getMail() public function getMail()
{ {
return $this->getComponent('mail'); return $this->get('mail');
} }
/** /**
...@@ -490,16 +500,16 @@ abstract class Application extends Module ...@@ -490,16 +500,16 @@ abstract class Application extends Module
*/ */
public function getAuthManager() public function getAuthManager()
{ {
return $this->getComponent('authManager'); return $this->get('authManager');
} }
/** /**
* Registers the core application components. * Returns the core application components.
* @see setComponents * @see set
*/ */
public function registerCoreComponents() public function coreComponents()
{ {
$this->setComponents([ return [
'log' => ['class' => 'yii\log\Logger'], 'log' => ['class' => 'yii\log\Logger'],
'errorHandler' => ['class' => 'yii\base\ErrorHandler'], 'errorHandler' => ['class' => 'yii\base\ErrorHandler'],
'formatter' => ['class' => 'yii\base\Formatter'], 'formatter' => ['class' => 'yii\base\Formatter'],
...@@ -507,7 +517,7 @@ abstract class Application extends Module ...@@ -507,7 +517,7 @@ abstract class Application extends Module
'mail' => ['class' => 'yii\swiftmailer\Mailer'], 'mail' => ['class' => 'yii\swiftmailer\Mailer'],
'urlManager' => ['class' => 'yii\web\UrlManager'], 'urlManager' => ['class' => 'yii\web\UrlManager'],
'view' => ['class' => 'yii\web\View'], 'view' => ['class' => 'yii\web\View'],
]); ];
} }
/** /**
......
...@@ -8,6 +8,8 @@ ...@@ -8,6 +8,8 @@
namespace yii\base; namespace yii\base;
use Yii; use Yii;
use yii\di\ContainerInterface;
use yii\di\ContainerTrait;
/** /**
* Module is the base class for module and application classes. * Module is the base class for module and application classes.
...@@ -35,8 +37,10 @@ use Yii; ...@@ -35,8 +37,10 @@ use Yii;
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
*/ */
class Module extends Component class Module extends Component implements ContainerInterface
{ {
use ContainerTrait;
/** /**
* @var array custom module parameters (name => value). * @var array custom module parameters (name => value).
*/ */
...@@ -110,10 +114,7 @@ class Module extends Component ...@@ -110,10 +114,7 @@ class Module extends Component
* @var array child modules of this module * @var array child modules of this module
*/ */
private $_modules = []; private $_modules = [];
/**
* @var array components registered under this module
*/
private $_components = [];
/** /**
* Constructor. * Constructor.
...@@ -130,15 +131,14 @@ class Module extends Component ...@@ -130,15 +131,14 @@ class Module extends Component
/** /**
* Getter magic method. * Getter magic method.
* This method is overridden to support accessing components * This method is overridden to support accessing components like reading properties.
* like reading module properties.
* @param string $name component or property name * @param string $name component or property name
* @return mixed the named property value * @return mixed the named property value
*/ */
public function __get($name) public function __get($name)
{ {
if ($this->hasComponent($name)) { if ($this->has($name)) {
return $this->getComponent($name); return $this->get($name);
} else { } else {
return parent::__get($name); return parent::__get($name);
} }
...@@ -146,15 +146,14 @@ class Module extends Component ...@@ -146,15 +146,14 @@ class Module extends Component
/** /**
* Checks if a property value is null. * Checks if a property value is null.
* This method overrides the parent implementation by checking * This method overrides the parent implementation by checking if the named component is loaded.
* if the named component is loaded.
* @param string $name the property name or the event name * @param string $name the property name or the event name
* @return boolean whether the property value is null * @return boolean whether the property value is null
*/ */
public function __isset($name) public function __isset($name)
{ {
if ($this->hasComponent($name)) { if ($this->has($name)) {
return $this->getComponent($name) !== null; return $this->get($name, [], false) !== null;
} else { } else {
return parent::__isset($name); return parent::__isset($name);
} }
...@@ -432,126 +431,14 @@ class Module extends Component ...@@ -432,126 +431,14 @@ class Module extends Component
} }
/** /**
* Checks whether the named component exists.
* @param string $id component ID
* @return boolean whether the named component exists. Both loaded and unloaded components
* are considered.
*/
public function hasComponent($id)
{
return isset($this->_components[$id]);
}
/**
* Retrieves the named component.
* @param string $id component ID (case-sensitive)
* @param boolean $load whether to load the component if it is not yet loaded.
* @return Component|null the component instance, null if the component does not exist.
* @see hasComponent()
*/
public function getComponent($id, $load = true)
{
if (isset($this->_components[$id])) {
if ($this->_components[$id] instanceof Object) {
return $this->_components[$id];
} elseif ($load) {
return $this->_components[$id] = Yii::createObject($this->_components[$id]);
}
}
return null;
}
/**
* Registers a component with this module.
* @param string $id component ID
* @param Component|array|null $component the component to be registered with the module. This can
* be one of the followings:
*
* - a [[Component]] object
* - a configuration array: when [[getComponent()]] is called initially for this component, the array
* will be used to instantiate the component via [[Yii::createObject()]].
* - null: the named component will be removed from the module
*/
public function setComponent($id, $component)
{
if ($component === null) {
unset($this->_components[$id]);
} else {
$this->_components[$id] = $component;
}
}
/**
* Returns the registered components.
* @param boolean $loadedOnly whether to return the loaded components only. If this is set false,
* then all components specified in the configuration will be returned, whether they are loaded or not.
* Loaded components will be returned as objects, while unloaded components as configuration arrays.
* @return array the components (indexed by their IDs)
*/
public function getComponents($loadedOnly = false)
{
if ($loadedOnly) {
$components = [];
foreach ($this->_components as $component) {
if ($component instanceof Component) {
$components[] = $component;
}
}
return $components;
} else {
return $this->_components;
}
}
/**
* Registers a set of components in this module.
*
* Each component should be specified as a name-value pair, where
* name refers to the ID of the component and value the component or a configuration
* array that can be used to create the component. In the latter case, [[Yii::createObject()]]
* will be used to create the component.
*
* If a new component has the same ID as an existing one, the existing one will be overwritten silently.
*
* The following is an example for setting two components:
*
* ~~~
* [
* 'db' => [
* 'class' => 'yii\db\Connection',
* 'dsn' => 'sqlite:path/to/file.db',
* ],
* 'cache' => [
* 'class' => 'yii\caching\DbCache',
* 'db' => 'db',
* ],
* ]
* ~~~
*
* @param array $components components (id => component configuration or instance)
*/
public function setComponents($components)
{
foreach ($components as $id => $component) {
if (!is_object($component) && isset($this->_components[$id]['class']) && !isset($component['class'])) {
// set default component class
$component['class'] = $this->_components[$id]['class'];
}
$this->_components[$id] = $component;
}
}
/**
* Loads components that are declared in [[preload]]. * Loads components that are declared in [[preload]].
* @throws InvalidConfigException if a component or module to be preloaded is unknown * @throws InvalidConfigException if a component or module to be preloaded is unknown
*/ */
public function preloadComponents() public function preloadComponents()
{ {
foreach ($this->preload as $id) { foreach ($this->preload as $id) {
if ($this->hasComponent($id)) { if ($this->has($id)) {
$this->getComponent($id); $this->get($id);
} elseif ($this->hasModule($id)) { } elseif ($this->hasModule($id)) {
$this->getModule($id); $this->getModule($id);
} else { } else {
......
...@@ -80,7 +80,7 @@ class DbCache extends Cache ...@@ -80,7 +80,7 @@ class DbCache extends Cache
{ {
parent::init(); parent::init();
if (is_string($this->db)) { if (is_string($this->db)) {
$this->db = Yii::$app->getComponent($this->db); $this->db = Yii::$app->get($this->db);
} }
if (!$this->db instanceof Connection) { if (!$this->db instanceof Connection) {
throw new InvalidConfigException("DbCache::db must be either a DB connection instance or the application component ID of a DB connection."); throw new InvalidConfigException("DbCache::db must be either a DB connection instance or the application component ID of a DB connection.");
......
...@@ -45,7 +45,7 @@ class DbDependency extends Dependency ...@@ -45,7 +45,7 @@ class DbDependency extends Dependency
*/ */
protected function generateDependencyData($cache) protected function generateDependencyData($cache)
{ {
$db = Yii::$app->getComponent($this->db); $db = Yii::$app->get($this->db);
if (!$db instanceof Connection) { if (!$db instanceof Connection) {
throw new InvalidConfigException("DbDependency::db must be the application component ID of a DB connection."); throw new InvalidConfigException("DbDependency::db must be the application component ID of a DB connection.");
} }
......
...@@ -154,7 +154,7 @@ class Application extends \yii\base\Application ...@@ -154,7 +154,7 @@ class Application extends \yii\base\Application
*/ */
public function getResponse() public function getResponse()
{ {
return $this->getComponent('response'); return $this->get('response');
} }
/** /**
...@@ -193,15 +193,13 @@ class Application extends \yii\base\Application ...@@ -193,15 +193,13 @@ class Application extends \yii\base\Application
} }
/** /**
* Registers the core application components. * @inheritdoc
* @see setComponents
*/ */
public function registerCoreComponents() public function coreComponents()
{ {
parent::registerCoreComponents(); return array_merge([
$this->setComponents([
'request' => ['class' => 'yii\console\Request'], 'request' => ['class' => 'yii\console\Request'],
'response' => ['class' => 'yii\console\Response'], 'response' => ['class' => 'yii\console\Response'],
]); ], parent::coreComponents());
} }
} }
...@@ -26,7 +26,7 @@ class CacheController extends Controller ...@@ -26,7 +26,7 @@ class CacheController extends Controller
public function actionIndex() public function actionIndex()
{ {
$caches = []; $caches = [];
$components = Yii::$app->getComponents(); $components = Yii::$app->getComponentDefinitions();
foreach ($components as $name => $component) { foreach ($components as $name => $component) {
if ($component instanceof Cache) { if ($component instanceof Cache) {
$caches[$name] = get_class($component); $caches[$name] = get_class($component);
...@@ -53,7 +53,7 @@ class CacheController extends Controller ...@@ -53,7 +53,7 @@ class CacheController extends Controller
public function actionFlush($component = 'cache') public function actionFlush($component = 'cache')
{ {
/** @var Cache $cache */ /** @var Cache $cache */
$cache = Yii::$app->getComponent($component); $cache = Yii::$app->get($component);
if (!$cache || !$cache instanceof Cache) { if (!$cache || !$cache instanceof Cache) {
throw new Exception('Application component "'.$component.'" is not defined or not a cache.'); throw new Exception('Application component "'.$component.'" is not defined or not a cache.');
} }
......
...@@ -129,7 +129,7 @@ class MessageController extends Controller ...@@ -129,7 +129,7 @@ class MessageController extends Controller
} }
} }
} elseif ($config['format'] === 'db') { } elseif ($config['format'] === 'db') {
$db = \Yii::$app->getComponent(isset($config['db']) ? $config['db'] : 'db'); $db = \Yii::$app->get(isset($config['db']) ? $config['db'] : 'db');
if (!$db instanceof \yii\db\Connection) { if (!$db instanceof \yii\db\Connection) {
throw new Exception('The "db" option must refer to a valid database application component.'); throw new Exception('The "db" option must refer to a valid database application component.');
} }
......
...@@ -122,7 +122,7 @@ class MigrateController extends Controller ...@@ -122,7 +122,7 @@ class MigrateController extends Controller
if ($action->id !== 'create') { if ($action->id !== 'create') {
if (is_string($this->db)) { if (is_string($this->db)) {
$this->db = Yii::$app->getComponent($this->db); $this->db = Yii::$app->get($this->db);
} }
if (!$this->db instanceof Connection) { if (!$this->db instanceof Connection) {
throw new Exception("The 'db' option must refer to the application component ID of a DB connection."); throw new Exception("The 'db' option must refer to the application component ID of a DB connection.");
......
...@@ -85,7 +85,7 @@ class ActiveDataProvider extends BaseDataProvider ...@@ -85,7 +85,7 @@ class ActiveDataProvider extends BaseDataProvider
{ {
parent::init(); parent::init();
if (is_string($this->db)) { if (is_string($this->db)) {
$this->db = Yii::$app->getComponent($this->db); $this->db = Yii::$app->get($this->db);
if ($this->db === null) { if ($this->db === null) {
throw new InvalidConfigException('The "db" property must be a valid DB Connection application component.'); throw new InvalidConfigException('The "db" property must be a valid DB Connection application component.');
} }
......
...@@ -90,7 +90,7 @@ class SqlDataProvider extends BaseDataProvider ...@@ -90,7 +90,7 @@ class SqlDataProvider extends BaseDataProvider
{ {
parent::init(); parent::init();
if (is_string($this->db)) { if (is_string($this->db)) {
$this->db = Yii::$app->getComponent($this->db); $this->db = Yii::$app->get($this->db);
} }
if (!$this->db instanceof Connection) { if (!$this->db instanceof Connection) {
throw new InvalidConfigException('The "db" property must be a valid DB Connection application component.'); throw new InvalidConfigException('The "db" property must be a valid DB Connection application component.');
......
...@@ -378,7 +378,7 @@ class Command extends \yii\base\Component ...@@ -378,7 +378,7 @@ class Command extends \yii\base\Component
/** @var \yii\caching\Cache $cache */ /** @var \yii\caching\Cache $cache */
if ($db->enableQueryCache && $method !== '') { if ($db->enableQueryCache && $method !== '') {
$cache = is_string($db->queryCache) ? Yii::$app->getComponent($db->queryCache) : $db->queryCache; $cache = is_string($db->queryCache) ? Yii::$app->get($db->queryCache) : $db->queryCache;
} }
if (isset($cache) && $cache instanceof Cache) { if (isset($cache) && $cache instanceof Cache) {
......
...@@ -49,7 +49,7 @@ class Migration extends \yii\base\Component ...@@ -49,7 +49,7 @@ class Migration extends \yii\base\Component
{ {
parent::init(); parent::init();
if ($this->db === null) { if ($this->db === null) {
$this->db = \Yii::$app->getComponent('db'); $this->db = \Yii::$app->get('db');
} }
} }
......
...@@ -96,7 +96,7 @@ abstract class Schema extends Object ...@@ -96,7 +96,7 @@ abstract class Schema extends Object
if ($db->enableSchemaCache && !in_array($name, $db->schemaCacheExclude, true)) { if ($db->enableSchemaCache && !in_array($name, $db->schemaCacheExclude, true)) {
/** @var Cache $cache */ /** @var Cache $cache */
$cache = is_string($db->schemaCache) ? Yii::$app->getComponent($db->schemaCache) : $db->schemaCache; $cache = is_string($db->schemaCache) ? Yii::$app->get($db->schemaCache) : $db->schemaCache;
if ($cache instanceof Cache) { if ($cache instanceof Cache) {
$key = $this->getCacheKey($name); $key = $this->getCacheKey($name);
if ($refresh || ($table = $cache->get($key)) === false) { if ($refresh || ($table = $cache->get($key)) === false) {
...@@ -225,7 +225,7 @@ abstract class Schema extends Object ...@@ -225,7 +225,7 @@ abstract class Schema extends Object
public function refresh() public function refresh()
{ {
/** @var Cache $cache */ /** @var Cache $cache */
$cache = is_string($this->db->schemaCache) ? Yii::$app->getComponent($this->db->schemaCache) : $this->db->schemaCache; $cache = is_string($this->db->schemaCache) ? Yii::$app->get($this->db->schemaCache) : $this->db->schemaCache;
if ($this->db->enableSchemaCache && $cache instanceof Cache) { if ($this->db->enableSchemaCache && $cache instanceof Cache) {
GroupDependency::invalidate($cache, $this->getCacheGroup()); GroupDependency::invalidate($cache, $this->getCacheGroup());
} }
......
...@@ -191,7 +191,7 @@ trait ContainerTrait ...@@ -191,7 +191,7 @@ trait ContainerTrait
$definition['class'] = $typeOrID; $definition['class'] = $typeOrID;
$this->_definitions[$typeOrID] = $definition; $this->_definitions[$typeOrID] = $definition;
} else { } else {
throw new InvalidConfigException("The configuration for \"$typeOrID\" must contain a \"class\" element."); throw new InvalidConfigException("The configuration for the \"$typeOrID\" component must contain a \"class\" element.");
} }
} else { } else {
// a type or ID // a type or ID
......
...@@ -94,14 +94,14 @@ class DbMessageSource extends MessageSource ...@@ -94,14 +94,14 @@ class DbMessageSource extends MessageSource
{ {
parent::init(); parent::init();
if (is_string($this->db)) { if (is_string($this->db)) {
$this->db = Yii::$app->getComponent($this->db); $this->db = Yii::$app->get($this->db);
} }
if (!$this->db instanceof Connection) { if (!$this->db instanceof Connection) {
throw new InvalidConfigException("DbMessageSource::db must be either a DB connection instance or the application component ID of a DB connection."); throw new InvalidConfigException("DbMessageSource::db must be either a DB connection instance or the application component ID of a DB connection.");
} }
if ($this->enableCaching) { if ($this->enableCaching) {
if (is_string($this->cache)) { if (is_string($this->cache)) {
$this->cache = Yii::$app->getComponent($this->cache); $this->cache = Yii::$app->get($this->cache);
} }
if (!$this->cache instanceof Cache) { if (!$this->cache instanceof Cache) {
throw new InvalidConfigException("DbMessageSource::cache must be either a cache object or the application component ID of the cache object."); throw new InvalidConfigException("DbMessageSource::cache must be either a cache object or the application component ID of the cache object.");
......
...@@ -63,7 +63,7 @@ class DbTarget extends Target ...@@ -63,7 +63,7 @@ class DbTarget extends Target
{ {
parent::init(); parent::init();
if (is_string($this->db)) { if (is_string($this->db)) {
$this->db = Yii::$app->getComponent($this->db); $this->db = Yii::$app->get($this->db);
} }
if (!$this->db instanceof Connection) { if (!$this->db instanceof Connection) {
throw new InvalidConfigException("DbTarget::db must be either a DB connection instance or the application component ID of a DB connection."); throw new InvalidConfigException("DbTarget::db must be either a DB connection instance or the application component ID of a DB connection.");
......
...@@ -44,7 +44,7 @@ class EmailTarget extends Target ...@@ -44,7 +44,7 @@ class EmailTarget extends Target
throw new InvalidConfigException('The "to" option must be set for EmailTarget::message.'); throw new InvalidConfigException('The "to" option must be set for EmailTarget::message.');
} }
if (is_string($this->mail)) { if (is_string($this->mail)) {
$this->mail = Yii::$app->getComponent($this->mail); $this->mail = Yii::$app->get($this->mail);
} }
if (!$this->mail instanceof MailerInterface) { if (!$this->mail instanceof MailerInterface) {
throw new InvalidConfigException("EmailTarget::mailer must be either a mailer object or the application component ID of a mailer object."); throw new InvalidConfigException("EmailTarget::mailer must be either a mailer object or the application component ID of a mailer object.");
......
...@@ -247,10 +247,10 @@ abstract class Target extends Component ...@@ -247,10 +247,10 @@ abstract class Target extends Component
$request = Yii::$app->getRequest(); $request = Yii::$app->getRequest();
$ip = $request instanceof Request ? $request->getUserIP() : '-'; $ip = $request instanceof Request ? $request->getUserIP() : '-';
/** @var \yii\web\User $user */ /** @var \yii\web\User $user */
$user = Yii::$app->getComponent('user', false); $user = Yii::$app->get('user', [], false);
$userID = $user ? $user->getId(false) : '-'; $userID = $user ? $user->getId(false) : '-';
/** @var \yii\web\Session $session */ /** @var \yii\web\Session $session */
$session = Yii::$app->getComponent('session', false); $session = Yii::$app->get('session', [], false);
$sessionID = $session && $session->getIsActive() ? $session->getId() : '-'; $sessionID = $session && $session->getIsActive() ? $session->getId() : '-';
return "[$ip] [$userID] [$sessionID]"; return "[$ip] [$userID] [$sessionID]";
} }
......
...@@ -32,7 +32,7 @@ abstract class DbMutex extends Mutex ...@@ -32,7 +32,7 @@ abstract class DbMutex extends Mutex
{ {
parent::init(); parent::init();
if (is_string($this->db)) { if (is_string($this->db)) {
$this->db = Yii::$app->getComponent($this->db); $this->db = Yii::$app->get($this->db);
} }
if (!$this->db instanceof Connection) { if (!$this->db instanceof Connection) {
throw new InvalidConfigException('Mutex::db must be either a DB connection instance or the application component ID of a DB connection.'); throw new InvalidConfigException('Mutex::db must be either a DB connection instance or the application component ID of a DB connection.');
......
...@@ -60,7 +60,7 @@ class DbManager extends Manager ...@@ -60,7 +60,7 @@ class DbManager extends Manager
public function init() public function init()
{ {
if (is_string($this->db)) { if (is_string($this->db)) {
$this->db = Yii::$app->getComponent($this->db); $this->db = Yii::$app->get($this->db);
} }
if (!$this->db instanceof Connection) { if (!$this->db instanceof Connection) {
throw new InvalidConfigException("DbManager::db must be either a DB connection instance or the application component ID of a DB connection."); throw new InvalidConfigException("DbManager::db must be either a DB connection instance or the application component ID of a DB connection.");
......
...@@ -35,7 +35,7 @@ abstract class DbFixture extends Fixture ...@@ -35,7 +35,7 @@ abstract class DbFixture extends Fixture
{ {
parent::init(); parent::init();
if (is_string($this->db)) { if (is_string($this->db)) {
$this->db = Yii::$app->getComponent($this->db); $this->db = Yii::$app->get($this->db);
} }
if (!is_object($this->db)) { if (!is_object($this->db)) {
throw new InvalidConfigException("The 'db' property must be either a DB connection instance or the application component ID of a DB connection."); throw new InvalidConfigException("The 'db' property must be either a DB connection instance or the application component ID of a DB connection.");
......
...@@ -129,7 +129,7 @@ class Application extends \yii\base\Application ...@@ -129,7 +129,7 @@ class Application extends \yii\base\Application
*/ */
public function getRequest() public function getRequest()
{ {
return $this->getComponent('request'); return $this->get('request');
} }
/** /**
...@@ -138,7 +138,7 @@ class Application extends \yii\base\Application ...@@ -138,7 +138,7 @@ class Application extends \yii\base\Application
*/ */
public function getResponse() public function getResponse()
{ {
return $this->getComponent('response'); return $this->get('response');
} }
/** /**
...@@ -147,7 +147,7 @@ class Application extends \yii\base\Application ...@@ -147,7 +147,7 @@ class Application extends \yii\base\Application
*/ */
public function getSession() public function getSession()
{ {
return $this->getComponent('session'); return $this->get('session');
} }
/** /**
...@@ -156,7 +156,7 @@ class Application extends \yii\base\Application ...@@ -156,7 +156,7 @@ class Application extends \yii\base\Application
*/ */
public function getUser() public function getUser()
{ {
return $this->getComponent('user'); return $this->get('user');
} }
/** /**
...@@ -165,22 +165,20 @@ class Application extends \yii\base\Application ...@@ -165,22 +165,20 @@ class Application extends \yii\base\Application
*/ */
public function getAssetManager() public function getAssetManager()
{ {
return $this->getComponent('assetManager'); return $this->get('assetManager');
} }
/** /**
* Registers the core application components. * @inheritdoc
* @see setComponents
*/ */
public function registerCoreComponents() public function coreComponents()
{ {
parent::registerCoreComponents(); return array_merge([
$this->setComponents([
'request' => ['class' => 'yii\web\Request'], 'request' => ['class' => 'yii\web\Request'],
'response' => ['class' => 'yii\web\Response'], 'response' => ['class' => 'yii\web\Response'],
'session' => ['class' => 'yii\web\Session'], 'session' => ['class' => 'yii\web\Session'],
'user' => ['class' => 'yii\web\User'], 'user' => ['class' => 'yii\web\User'],
'assetManager' => ['class' => 'yii\web\AssetManager'], 'assetManager' => ['class' => 'yii\web\AssetManager'],
]); ], parent::coreComponents());
} }
} }
...@@ -53,7 +53,7 @@ class CacheSession extends Session ...@@ -53,7 +53,7 @@ class CacheSession extends Session
public function init() public function init()
{ {
if (is_string($this->cache)) { if (is_string($this->cache)) {
$this->cache = Yii::$app->getComponent($this->cache); $this->cache = Yii::$app->get($this->cache);
} }
if (!$this->cache instanceof Cache) { if (!$this->cache instanceof Cache) {
throw new InvalidConfigException('CacheSession::cache must refer to the application component ID of a cache object.'); throw new InvalidConfigException('CacheSession::cache must refer to the application component ID of a cache object.');
......
...@@ -75,7 +75,7 @@ class DbSession extends Session ...@@ -75,7 +75,7 @@ class DbSession extends Session
public function init() public function init()
{ {
if (is_string($this->db)) { if (is_string($this->db)) {
$this->db = Yii::$app->getComponent($this->db); $this->db = Yii::$app->get($this->db);
} }
if (!$this->db instanceof Connection) { if (!$this->db instanceof Connection) {
throw new InvalidConfigException("DbSession::db must be either a DB connection instance or the application component ID of a DB connection."); throw new InvalidConfigException("DbSession::db must be either a DB connection instance or the application component ID of a DB connection.");
......
...@@ -145,7 +145,7 @@ class UrlManager extends Component ...@@ -145,7 +145,7 @@ class UrlManager extends Component
return; return;
} }
if (is_string($this->cache)) { if (is_string($this->cache)) {
$this->cache = Yii::$app->getComponent($this->cache); $this->cache = Yii::$app->get($this->cache);
} }
if ($this->cache instanceof Cache) { if ($this->cache instanceof Cache) {
$key = __CLASS__; $key = __CLASS__;
......
...@@ -82,7 +82,7 @@ class FragmentCache extends Widget ...@@ -82,7 +82,7 @@ class FragmentCache extends Widget
if (!$this->enabled) { if (!$this->enabled) {
$this->cache = null; $this->cache = null;
} elseif (is_string($this->cache)) { } elseif (is_string($this->cache)) {
$this->cache = Yii::$app->getComponent($this->cache); $this->cache = Yii::$app->get($this->cache);
} }
if ($this->getCachedContent() === false) { if ($this->getCachedContent() === false) {
......
...@@ -68,7 +68,7 @@ class MessageTest extends VendorTestCase ...@@ -68,7 +68,7 @@ class MessageTest extends VendorTestCase
*/ */
protected function createTestMessage() protected function createTestMessage()
{ {
return Yii::$app->getComponent('mail')->compose(); return Yii::$app->get('mail')->compose();
} }
/** /**
......
...@@ -59,7 +59,7 @@ class BaseMailerTest extends TestCase ...@@ -59,7 +59,7 @@ class BaseMailerTest extends TestCase
*/ */
protected function getTestMailComponent() protected function getTestMailComponent()
{ {
return Yii::$app->getComponent('mail'); return Yii::$app->get('mail');
} }
// Tests : // Tests :
......
...@@ -36,7 +36,7 @@ class BaseMessageTest extends TestCase ...@@ -36,7 +36,7 @@ class BaseMessageTest extends TestCase
*/ */
protected function getMailer() protected function getMailer()
{ {
return Yii::$app->getComponent('mail'); return Yii::$app->get('mail');
} }
// Tests : // Tests :
......
...@@ -58,7 +58,7 @@ class ActiveFixtureTest extends DatabaseTestCase ...@@ -58,7 +58,7 @@ class ActiveFixtureTest extends DatabaseTestCase
public function setUp() public function setUp()
{ {
parent::setUp(); parent::setUp();
\Yii::$app->setComponent('db', $this->getConnection()); \Yii::$app->set('db', $this->getConnection());
ActiveRecord::$db = $this->getConnection(); ActiveRecord::$db = $this->getConnection();
} }
......
...@@ -15,7 +15,7 @@ class CacheSessionTest extends \yiiunit\TestCase ...@@ -15,7 +15,7 @@ class CacheSessionTest extends \yiiunit\TestCase
{ {
parent::setUp(); parent::setUp();
$this->mockApplication(); $this->mockApplication();
Yii::$app->setComponent('cache', new FileCache()); Yii::$app->set('cache', new FileCache());
} }
public function testCacheSession() public function testCacheSession()
......
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