Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to access Yii2 components in your modules?

Tags:

php

yii2

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' => 'app\modules\fooModule\Module',
         'components'=>array(
            'testComponent'=>array(
                'class'=>'app\modules\fooModule\components\testComponent',
            ),
        ),
    ),
),

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

TestComponet.php has a class test which extend \yii\base\Component. See below

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!!';     
        }

}

How do i access test class in fooModule Controller ?

like image 361
chapskev Avatar asked Jan 12 '16 09:01

chapskev


People also ask

What is controller in Yii?

The yii\base\Controller::init() method is called after the controller is created and configured. The controller creates an action object based on the requested action ID: If the action ID is not specified, the default action ID will be used.


2 Answers

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

like image 144
Onedev_Link Avatar answered Sep 20 '22 07:09

Onedev_Link


The most elegant way to access module component from module controller without hardcoding module's ID is as follows:

$this->module->testComponent->exampleFunction();
like image 27
Kolyunya Avatar answered Sep 19 '22 07:09

Kolyunya