Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create modules in YII2

Tags:

php

yii2

How to create a module in yii2 and setting up the same on configuration. I've been searching a while on google and I cannot find that much tutorial on it. Please help.

like image 618
user2959221 Avatar asked Jul 01 '14 13:07

user2959221


People also ask

What is a Yii module?

Modules are self-contained software units that consist of models, views, controllers, and other supporting components. End users can access the controllers of a module when it is installed in application. For these reasons, modules are often viewed as mini-applications.


2 Answers

Option 1

  1. Create a modules folder on your application base path. This would be what corresponds to your @app alias of your currently running application. This is the same as the root folder of basic template or backend/frontend in the advanced template.

  2. Inside your modules folder create a folder for your module corresponding to the Module ID.

  3. Your Module Class should be inside this module folder and should extend \yii\base\Module. This is a basic working example for your module class.

    <?php
    
    namespace app\modules\home;
    
    class Home extends \yii\base\Module
    {
       public $controllerNamespace = 'app\modules\home\controllers';
    
       public function init()
       {
           parent::init();
    
           // custom initialization code goes here
       }
    }
    
  4. Create your module controller, models and views folder on the same folder.

  5. To access the module, you need to add this to your application configuration:

    <?php
    ......
       'modules' => [
          'home' => [
             'class' => 'app\modules\home\Home',
          ],
       ],
    ......
    

Option 2

  1. If you are using Gii module, go to module generator and enter path to module class. This would be the same as app\modules\home\Home in option 1

  2. Preview and Generate all files. Change application configuration as in Option 1 according to your module class.

like image 165
Zack Avatar answered Sep 30 '22 13:09

Zack


  1. Install Gii in yii2. Use documentation.
  2. Then use module generator. You need the web permission to create the file for the the folder OR you can copy paste the generated code and create the specified file manually.
  3. When generation is complete it will show you a green text. For try module" (When folder have the web permission) OR Copy following code to main.php configuration file under module. Replace modulename with yours.

    'modules' => [
        'modulename' => [
             'class' => 'app\modules\modulename\Module',
        ],
    ]
    

Please leave comment if still have confusion. I will edit to make this more sense.

like image 37
Kshitiz Avatar answered Sep 30 '22 14:09

Kshitiz