phpyii2componentsyii-components

What is local component in Yii2?


In the documentation "info" section Yii 2 says:

Using too many application components can potentially make your code harder to test and maintain. In many cases, you can simply create a local component and use it when needed.

What is local component? How create it?


Solution

  • Local component it is just local instance of component. So instead using:

    $value = Yii::$app->cache123->get($key);
    

    which will force you to define cache123 component in app config, you can use local instance:

    $cache = new ApcCache();
    $value = $cache->get($key);
    

    Or assign it to module for example:

    class MyModule extends \yii\base\Module {
    
        private $_cache;
    
        public function getCache(): \yii\caching\Cache {
            if ($this->_cache === null) {
                $this->_cache = new ApcCache();
            }
    
            return $this->_cache;
        }
    }
    

    And then in controller you can use:

    $value = $this->module->getCache()->get($key);
    

    You can also define components in module config:

    'modules' => [
        'myModule' => [
            'class' => MyModule::class,
            'components' => [
                'cache' => FileCache::class,
            ],
        ],
    ],
    

    And then in controller you can use:

    $value = $this->module->cache->get($key);
    

    In this way you can split your app into multiple independent modules with separate components. It may be easier to maintain this if you have large number of components if they're grouped in modules, especially if some of them are used only in one place or one module.