You may use Instance::get to obtain the actual object referenced by [[id]].
Instance is mainly used in two places:
- When configuring a dependency injection container, you use Instance to reference a class name, interface name
or alias name. The reference can later be resolved into the actual object by the container.
- In classes which use service locator to obtain dependent objects.
The following example shows how to configure a DI container with Instance:
php
$container = new \yii\di\Container;
$container->set('cache', [
'class' => 'yii\caching\DbCache',
'db' => Instance::of('db')
]);
$container->set('db', [
'class' => 'yii\db\Connection',
'dsn' => 'sqlite:path/to/file.db',
]);
And the following example shows how a class retrieves a component from a service locator:
php
class DbCache extends Cache
{
public $db = 'db';
public function init()
{
parent::init();
$this->db = Instance::ensure($this->db, 'yii\db\Connection');
}
}
public function init() { parent::init(); if ($this->userConfig !== null) { $this->userConfig = Instance::ensure($this->userConfig, UserConfig::className()); } }
public function getCache() { if (!is_object($this->_cache)) { $this->_cache = Instance::ensure($this->_cache, Cache::class); } return $this->_cache; }
/** * @return object * @throws \yii\base\InvalidConfigException */ protected static function getSession() { if (is_null(static::$session)) { static::$session = Instance::ensure(static::$session, Session::className()); } return static::$session; }
public function init() { parent::init(); $db = Instance::ensure($this->db, Connection::className()); $query = new Query(); $this->ticket = $query->select(['*'])->from($this->table)->createCommand($db)->queryAll(); }
/** * @throws \yii\base\InvalidConfigException */ public function init() { parent::init(); if (!empty($this->cache)) { $this->cache = Instance::ensure($this->cache, Cache::className()); } }
/** * @inheritdoc */ public function init() { parent::init(); $this->mailer = Instance::ensure($this->mailer, 'im\\users\\components\\UserMailerInterface'); Event::on(User::className(), User::EVENT_BEFORE_REGISTRATION, [$this, 'beforeUserRegistration']); Event::on(User::className(), User::EVENT_AFTER_REGISTRATION, [$this, 'afterUserRegistration']); }
/** * Get user * @return User */ public function getUser() { if (!$this->_user instanceof User) { $this->_user = Instance::ensure($this->_user, User::className()); } return $this->_user; }
public function beforeAction($action) { if (!$this->enabled) { return true; } $this->cache = Instance::ensure($this->cache, Cache::className()); $this->cache->cachePath = Yii::getAlias($this->cachePath) . '/' . $action->getUniqueId(); if (is_array($this->dependency)) { $this->dependency = Yii::createObject($this->dependency); } $properties = []; foreach (['cache', 'duration', 'dependency', 'variations'] as $name) { $properties[$name] = $this->{$name}; } $id = $this->varyByRoute ? $action->getUniqueId() : __CLASS__; $response = Yii::$app->getResponse(); ob_start(); ob_implicit_flush(false); if ($this->view->beginCache($id, $properties)) { $response->on(Response::EVENT_AFTER_SEND, [$this, 'cacheResponse']); return true; } else { $data = $this->cache->get($this->calculateCacheKey()); if (is_array($data)) { $this->restoreResponse($response, $data); } $response->content = ob_get_clean(); return false; } }
public function init() { if (null !== $this->cache) { $this->cache = Instance::ensure($this->cache, Cache::className()); } parent::init(); }
public function __construct($db = 'db') { $this->db = Instance::ensure($db, Connection::className()); $this->generator = new Generator(); $this->dbHelper = new Migration(['db' => $this->db]); $this->generatorConfigurator = new GeneratorConfigurator(); }
/** * @return \yii\httpclient\Client */ public function getHttpClient() { if (!is_object($this->_httpClient)) { $this->_httpClient = Instance::ensure($this->_httpClient, Client::className()); } return $this->_httpClient; }
/** * @throws \yii\base\InvalidConfigException */ public function init() { foreach ($this->locators as $k => $config) { $this->locators[$k] = Instance::ensure($config, 'trntv\\bus\\interfaces\\HandlerLocator'); } parent::init(); }
/** * 初始化方法 */ public function init() { parent::init(); //获取user实例 $this->user = Instance::ensure($this->user, User::className()); $this->user_info = $this->user->identity; }
public function interception($event) { if (!isset(Yii::$app->i18n->translations['db_rbac'])) { Yii::$app->i18n->translations['db_rbac'] = ['class' => 'yii\\i18n\\PhpMessageSource', 'sourceLanguage' => 'ru-Ru', 'basePath' => '@developeruz/db_rbac/messages']; } $route = Yii::$app->getRequest()->resolve(); //Проверяем права по конфигу $this->createRule(); $user = Instance::ensure(Yii::$app->user, User::className()); $request = Yii::$app->getRequest(); $action = $event->action; if (!$this->cheсkByRule($action, $user, $request)) { //И по AuthManager if (!$this->checkPermission($route)) { //Если задан $login_url и пользователь не авторизован if (Yii::$app->user->isGuest && $this->login_url) { Yii::$app->response->redirect($this->login_url)->send(); exit; } //Если задан $redirect_url if ($this->redirect_url) { Yii::$app->response->redirect($this->redirect_url)->send(); exit; } else { throw new ForbiddenHttpException(Yii::t('db_rbac', 'Недостаточно прав')); } } } }
/** * Initializes the DB connection component. * This method will initialize the [[db]] property to make sure it refers to a valid DB connection. * @throws InvalidConfigException if [[db]] is invalid. */ public function init() { parent::init(); if (is_string($this->api)) { $this->api = Instance::ensure($this->api, Connection::className()); } }
/** * Initializes the action. * @throws InvalidConfigException if the xmlpipe document does not exist. */ public function init() { if ($this->document === null) { throw new InvalidConfigException(get_class($this) . '::$document must be set.'); } $this->document = Instance::ensure($this->document, BaseXmlPipe::className()); }
/** * Initializes the migration. * This method will set [[db]] to be the 'db' application component, if it is `null`. */ public function init() { parent::init(); $this->db = Instance::ensure($this->db, Connection::className()); $this->db->getSchema()->refresh(); $this->db->enableSlaves = false; }
public function init() { parent::init(); $this->i2db = Instance::ensure($this->i2db, Connection::className()); $this->infodb = Instance::ensure($this->infodb, Connection::className()); $this->db46 = Instance::ensure($this->db46, Connection::className()); }
/** * Initializes the application component. * This method overrides the parent implementation by establishing the database connection. */ public function init() { parent::init(); $this->db = Instance::ensure($this->db, Connection::className()); $this->db->getCollection($this->itemTable)->createIndex(['name' => 1], ['unique' => true]); $this->db->getCollection($this->ruleTable)->createIndex(['name' => 1], ['unique' => true]); }
/** * @inheritdoc */ public function init() { parent::init(); if (empty($this->message['to'])) { throw new InvalidConfigException('The "to" option must be set for EmailTarget::message.'); } $this->mailer = Instance::ensure($this->mailer, 'yii\\mail\\MailerInterface'); }
/** * @inheritdoc */ public function init() { parent::init(); $this->ssh = Instance::ensure($this->ssh, Connection::className()); if ($this->basePath === null) { $this->basePath = '/home/' . $this->ssh->username . '/files'; } }
public function testEnsure() { $container = new Container(); $container->set('db', ['class' => 'yii\\db\\Connection', 'dsn' => 'test']); $this->assertTrue(Instance::ensure('db', 'yii\\db\\Connection', $container) instanceof Connection); $this->assertTrue(Instance::ensure(new Connection(), 'yii\\db\\Connection', $container) instanceof Connection); $this->assertTrue(Instance::ensure(['class' => 'yii\\db\\Connection', 'dsn' => 'test'], 'yii\\db\\Connection', $container) instanceof Connection); }
/** * Initializes the DbMessageSource component. * This method will initialize the [[db]] property to make sure it refers to a valid DB connection. * Configured [[cache]] component would also be initialized. * @throws InvalidConfigException if [[db]] is invalid or [[cache]] is invalid. */ public function init() { parent::init(); $this->db = Instance::ensure($this->db, Connection::className()); if ($this->enableCaching) { $this->cache = Instance::ensure($this->cache, Cache::className()); } }
/** * @return IUserNotificator */ public function getNotificator() { if (!isset($this->_notificator)) { $this->_notificator = Yii::createObject($this->components['notificator']); Instance::ensure($this->_notificator, 'nkostadinov\\user\\interfaces\\IUserNotificator'); } return $this->_notificator; }
public function actionFlushCache($component = 'cache') { /** @var Cache $cache */ $cache = Instance::ensure($component, Cache::className()); $cache->flush(); Yii::$app->session->setFlash(Alert::TYPE_SUCCESS, Yii::t('gromver.platform', 'Cache flushed.')); return $this->redirect(['index']); }
/** * Initializes the [[rules]] array by instantiating rule objects from configurations. */ public function init() { parent::init(); $this->user = Instance::ensure($this->user, User::className()); if ($this->user->identity !== null) { $this->user->identity->getRules(); } }
/** * @inheritdoc */ public function init() { parent::init(); $this->db = Instance::ensure($this->db, Connection::className()); if (is_string($this->cache)) { $this->cache = Yii::$app->get($this->cache, false); } }
/** * Initialize the component */ public function init() { parent::init(); if ($this->cache !== null) { $this->cache = Instance::ensure($this->cache, Cache::className()); } $this->model = new $this->modelClass(); }
/** * Singleton construct. */ protected function __construct() { try { $this->cache = Instance::ensure($this->cache, DefaultCache::className()); } catch (Exception $e) { $this->cache = new DummyCache(); } }
public function init() { $this->db = Instance::ensure($this->db, Connection::className()); parent::init(); // Note the default configuration data value will not store to database. $this->data = array_merge($this->loadData(), $this->data); }