A module resides in the main application and organized as a directory that is called base path of the module. This module directory will have its own MVC (model, view and controller) and other supporting components just like an application.


Module Structure

Modules follow a typical structure as shown below.

  1. newModule/  
  2.     Module.php                   the module class file  
  3.     controllers/                 containing controller class files  
  4.         DefaultController.php    the default controller class file  
  5.     models/                      containing model class files  
  6.     views/                       containing controller view and layout files  
  7.         layouts/                 containing layout view files  
  8.         default/                 containing view files for DefaultController  
  9.             index.php            the index view file  

Module Class

Module class characteristics:

  • Each module should have a unique class extending to yii\base\Module.
  • Class should be located under module's base path and should be accessible.
  • On execution, a single instance of the module class will be created.
  • Module instances are used to share data and components for codes within modules.
  • By default it is named as Module.php.

Example

Let's look at an example to create a module.

Step 1 Create modules named folder in Frontend directory of your Yii2 folder.

Step 2 Inside modules folder create a folder named as project.

Step 3 Inside project folder create a file named as Project.php.

  1. <?php   
  2.   
  3. namespace frontend\modules\project;   
  4.   
  5. /**  
  6.  * project module definition class  
  7.  */   
  8. class Project extends \yii\base\Module   
  9. {   
  10.     /**  
  11.      * @inheritdoc  
  12.      */   
  13.     public $controllerNamespace = 'frontend\modules\project\controllers';   
  14.   
  15.     /**  
  16.      * @inheritdoc  
  17.      */   
  18.     public function init()   
  19.     {   
  20.         parent::init();   
  21.   
  22.         // custom initialization code goes here   
  23.     }   
  24. }   

Look at the above code, this is module class we have created. The init() function here is to initialize the module's properties.

Step 4 Inside project folder create two more folders named as controllers and views.

Step 5 Inside controllers folder create EmpController.php file.

  1. <?php   
  2.   
  3. namespace frontend\modules\project\controllers;   
  4.   
  5. use yii\web\Controller;   
  6.   
  7. /**  
  8.  * Default controller for the `project` module  
  9.  */   
  10. class EmpController extends Controller   
  11. {   
  12.     /**  
  13.      * Renders the index view for the module  
  14.      * @return string  
  15.      */   
  16.     public function actionMessage()   
  17.     {   
  18.         return $this->render('message');   
  19.     }   
  20. }   

Look at the above snapshot, here we have defined the action actionMessage.

Step 6 Inside views folder create emp folder and inside it create message.php file.

<h1>This is an Example to create a Module.</h1>

The below snapshot shows our final modules's structure in our modd directory. It displays all the files created inside modd/frontend/modules directory.

YII Moudles 1

Step 7 Now we need to do some config settings to add our module. Go to config folder of frontend directory.

Add the module in the file main.php in the config folder.

  1. <?php   
  2. $params = array_merge(   
  3.     require(__DIR__ . '/../../common/config/params.php'),   
  4.     require(__DIR__ . '/../../common/config/params-local.php'),   
  5.     require(__DIR__ . '/params.php'),   
  6.     require(__DIR__ . '/params-local.php')   
  7. );   
  8.   
  9. return [   
  10.     'id' => 'app-frontend',   
  11.     'basePath' => dirname(__DIR__),   
  12.     'bootstrap' => ['log'],   
  13.     'controllerNamespace' => 'frontend\controllers',   
  14.      'modules' => [   
  15.         'project' =>[   
  16.             'class' => 'frontend\modules\project\Project',   
  17.        ],   
  18.     ],   
  19.     'components' => [   
  20.         'request' => [   
  21.             'csrfParam' => '_csrf-frontend',   
  22.         ],   
  23.         'user' => [   
  24.             'identityClass' => 'common\models\User',   
  25.             'enableAutoLogin' => true,   
  26.             'identityCookie' => ['name' => '_identity-frontend''httpOnly' => true],   
  27.         ],   
  28.         'session' => [   
  29.             // this is the name of the session cookie used for login on the frontend   
  30.             'name' => 'advanced-frontend',   
  31.         ],   
  32.         'log' => [   
  33.             'traceLevel' => YII_DEBUG ? 3 : 0,   
  34.             'targets' => [   
  35.                 [   
  36.                     'class' => 'yii\log\FileTarget',   
  37.                     'levels' => ['error''warning'],   
  38.                 ],   
  39.             ],   
  40.         ],   
  41.         'errorHandler' => [   
  42.             'errorAction' => 'site/error',   
  43.         ],   
  44.         /*  
  45.         'urlManager' => [  
  46.             'enablePrettyUrl' => true,  
  47.             'showScriptName' => false,  
  48.             'rules' => [  
  49.             ],  
  50.         ],  
  51.         */   
  52.     ],   
  53.     'params' => $params,   
  54. ];   

Step 8 Run it on the browser with the following URL,

http://localhost/modd/frontend/web/index.php?r=project/emp/message

YII Moudles 2

Important Points:

  • Modules should be used for large applications. Divide its features into several groups and develop them as a module.
  • Modules should be reusable for the future projects.