Skip to content
Advertisement

Correct way to access Yii2 components in your modules?

I have created and configured a module fooModule. I need to create a component inside the module.

This is my configuration for my module in main.php

'modules'=>array(
    'fooModule'=>array(
         'class' => 'appmodulesfooModuleModule',
         'components'=>array(
            'testComponent'=>array(
                'class'=>'appmodulesfooModulecomponentstestComponent',
            ),
        ),
    ),
),

In the folder module fooModule i have created a folder components with a file testComponent.php

TestComponet.php has a class test which extend yiibaseComponent. See below

namespace appmodulesfooModulecomponent;

class test extends yiibaseComponent {

        public function __construct() {
                private $bar;     
        }

        public function exampleFunction() {
                echo 'am alive, come and look for me please!!';     
        }

}

How do i access test class in fooModule Controller ?

Advertisement

Answer

Use Yii::$app->getModule('fooModule')->testComponent->exampleFunction(); for access module component.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement