访问模块中Yii2组件的正确方式


Correct way to access Yii2 components in your modules?

我已经创建并配置了一个模块fooModule。我需要在模块中创建一个组件。

这是我在main.php 中的模块配置

'modules'=>array(
    'fooModule'=>array(
         'class' => 'app'modules'fooModule'Module',
         'components'=>array(
            'testComponent'=>array(
                'class'=>'app'modules'fooModule'components'testComponent',
            ),
        ),
    ),
),

在文件夹模块fooModule中,我创建了一个文件夹组件,文件为testComponent.php

TestComponent.php有一个扩展''yii''base''Component的类测试。见下文

namespace app'modules'fooModule'component;
class test extends 'yii'base'Component {
        public function __construct() {
                private $bar;     
        }
        public function exampleFunction() {
                echo 'am alive, come and look for me please!!';     
        }
}

如何访问fooModule Controller中的测试类?

访问模块组件使用Yii::$app->getModule('fooModule')->testComponent->exampleFunction();

从模块控制器访问模块组件而无需对模块ID进行硬编码的最优雅方法如下:

$this->module->testComponent->exampleFunction();

这看起来非常优雅的

Module::getInstance()->testComponent