【问题标题】:Correct way to access Yii2 components in your modules?访问模块中 Yii2 组件的正确方法?
【发布时间】:2016-04-16 21:00:58
【问题描述】:

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

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

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

在文件夹模块 fooModule 中,我创建了一个文件夹 components,其中包含一个文件 testComponent.php

TestComponet.php 有一个类 test,它扩展了 \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 中的测试类?

【问题讨论】:

    标签: php yii2


    【解决方案1】:

    这看起来很优雅

    Module::getInstance()->testComponent
    

    【讨论】:

      【解决方案2】:

      无需硬编码模块ID即可从模块控制器访问模块组件的最优雅方式如下:

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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

        • 感谢您的回复让我试试
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-11-28
        • 1970-01-01
        • 2019-10-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多