Yii 1.1: How to access a component of a module from within the module itself

6 followers

The Yii documentation states:

An application module may be considered as a self-contained sub-application that has its own controllers, models and views and can be reused in a different project as a whole. Controllers inside a module must be accessed with routes that are prefixed with the module ID.

So, in practice, a module can be handled like an application, but with minor differences.

Suppose you had a custom component 'foo' in your application:

return array(
    'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
    'preload'=>array('log'),
    'import'=>array(
        'application.models.*',
        'application.components.*'
    ),
    'components'=>array(
        'db'=>array(
        ),
        //right down here:
        'foo' => array(
            'param1' => 'val1'
        )
    ),

...and you need to move it inside a module called 'bar':

return array(
        'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
        'preload'=>array('log'),
        'import'=>array(
            'application.models.*',
            'application.components.*'
        ),
        'components'=>array(
            'db'=>array(
            )
        ),
        'modules' => array(
            'bar' => array(
                'components' => array(
                    'foo' => array(
                        'param1' => 'val1'
                    )
 
                )
            )
        )
    //...

Now instead of using the component:

Yii::app()->foo

You call it from within the module:

Yii::app()->controller->module->foo

or

Yii::app()->getModule('module')->foo

As you can see, your module is indeed just another application, and you can configure any parameters as you'd do with your "root" application. The only organizational differences are:

  • a module has a module "entry point", the FooModule which extends CWebModule. Whereas the root application is bootstrapped by the framework itself, starting with your entry script (index.php)
  • the application's SiteController is called inside a module DefaultController

Total 3 comments

#16041 report it
ametad at 2014/01/14 04:46am
syntax

In your example:

Yii::app()->getModule('module')->foo

Must be:

Yii::app()->getModule('bar')->foo

Thank you for explaining how this goes in Yii!

#15147 report it
Ulashev Roman at 2013/10/11 01:58pm
Thanks

Saved a lot of time, mate :)

#1721 report it
will at 2009/04/28 03:27pm
An alternative (better) way to call

Use Yii::app()->getModule('bar')->foo to access 'foo' components, so that you can do it across the whole project while Yii::app()->controller->module->foo only works if it's in 'bar' module.

Leave a comment

Please to leave your comment.

Write new article