Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Yii2中的本地组件是什么?_Php_Yii2_Components_Yii Components - Fatal编程技术网

Php Yii2中的本地组件是什么?

Php Yii2中的本地组件是什么?,php,yii2,components,yii-components,Php,Yii2,Components,Yii Components,在“信息”部分,Yii 2说: 使用太多的应用程序组件可能会使代码更难测试和维护。在许多情况下,您可以简单地创建一个本地组件,并在需要时使用它 什么是本地组件?如何创建它?本地组件它只是组件的本地实例。因此,使用: $value = Yii::$app->cache123->get($key); 这将强制您在应用程序配置中定义cache123组件,您可以使用本地实例: $cache = new ApcCache(); $value = $cache->get($key);

在“信息”部分,Yii 2说:

使用太多的应用程序组件可能会使代码更难测试和维护。在许多情况下,您可以简单地创建一个本地组件,并在需要时使用它


什么是本地组件?如何创建它?

本地组件它只是组件的本地实例。因此,使用:

$value = Yii::$app->cache123->get($key);
这将强制您在应用程序配置中定义
cache123
组件,您可以使用本地实例:

$cache = new ApcCache();
$value = $cache->get($key);
或将其分配给模块,例如:

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;
    }
}
然后在控制器中,您可以使用:

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

您还可以在模块配置中定义组件:

'modules' => [
    'myModule' => [
        'class' => MyModule::class,
        'components' => [
            'cache' => FileCache::class,
        ],
    ],
],
然后在控制器中,您可以使用:

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

通过这种方式,您可以将应用程序拆分为多个独立的模块,其中包含独立的组件。如果将大量组件分组到模块中,尤其是其中一些组件仅在一个位置或一个模块中使用,则可能更容易维护此功能。

请将链接发布到文档。在“信息”部分