Modules

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.

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.

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.

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.

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.
Next TopicYII Widgets




Latest Courses