yii\di\ServiceLocator::set PHP Method

set() public method

For example, php a class name $locator->set('cache', 'yii\caching\FileCache'); a configuration array $locator->set('db', [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=127.0.0.1;dbname=demo', 'username' => 'root', 'password' => '', 'charset' => 'utf8', ]); an anonymous function $locator->set('cache', function ($params) { return new \yii\caching\FileCache; }); an instance $locator->set('cache', new \yii\caching\FileCache); If a component definition with the same ID already exists, it will be overwritten.
public set ( string $id, mixed $definition )
$id string component ID (e.g. `db`).
$definition mixed the component definition to be registered with this locator. It can be one of the following: - 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. - 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.
    public function set($id, $definition)
    {
        if ($definition === null) {
            unset($this->_components[$id], $this->_definitions[$id]);
            return;
        }
        unset($this->_components[$id]);
        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));
        }
    }

Usage Example

コード例 #1
0
 /**
  * Get twocheckout return class instance
  *
  * @access public
  * @return \yii\twocheckout\TwoCheckoutReturn
  */
 public function getReturn()
 {
     if (!$this->locator->has('return')) {
         $this->locator->set('return', '\\yii\\twocheckout\\TwoCheckoutReturn');
     }
     return $this->locator->get('return');
 }
All Usage Examples Of yii\di\ServiceLocator::set