Creating modules

A module is practically an application inside the main application. In fact, it is organized as a directory that is called the base path of the module. Within the directory, there are folders containing its controllers, models, views, and other code, just like in an application.

Follow the typical structure of a module:

myCustomModule/
    Module.php                   the module class file
    controllers/                 containing controller class files
        DefaultController.php    the default controller class file
    models/                      containing model class files
    views/                       containing controller view and layout files
        layouts/                 containing layout view files
        default/                 containing view files for DefaultController
            index.php            the index view file

The module class file is instanced when a module is being accessed and it is used to share data and components for code, such as application instances.

The module class file has these characteristics:

  • It is by default named Module.php
  • It is instanced once during the code execution
  • It is located directly under the module's base path
  • It extends from yiiaseModule

Let's look at an example of a module class for myCustomModule (under the appmodulesmyCustomModule namespace):

namespace appmodulesmyCustomModule;

class Module extends yiiaseModule
{
    public function init()
    {
        parent::init();

        $this->params['foo'] = 'bar';
        // ...  other initialization code ...
    }
}

As a standard application, a module can have its own configuration based on a config file that has the same contents of a standard application:

<?php
return [
    'components' => [
        // list of component configurations
    ],
    'params' => [
        // list of parameters
    ],
  ..
  ..
  ..
];

We load this in the init() method of the module:

public function init()
{
    parent::init();
    // initialize the module with the configuration loaded from config.php
    Yii::configure($this, require(__DIR__ . '/config.php'));
}

Then, we create and use controllers, models, and views in the same way we do with a normal application.

Note

We always have to take care to specify the right namespace at the top of every file.

Finally, to use a module in an application, we simply configure the application by listing the module in the module's property of the application. The following code in the application configuration uses the forum module:

[
    'modules' => [
        'myCustomModule' => [
            'class' => 'appmodulesmyCustomModuleModule',
            // ... other configurations for the module ...
        ],
    ],
]
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.132.214