Yii  framework is a fast and secure framework for developing PHP applications. A module in Yii is a self-contained application unit which comprises several supporting features, models, controllers and views.

Create Module:

A module is organized as a directory whose name serves as its unique ID.
Structure of module:
example/
ExampleModule.php  –  the module class file
components/  –   containing reusable user components
views/   –  containing view files for widgets
controllers/  –  containing controller class files
DefaultController.php  –   the default controller class file
extensions/ – containing third-party extensions
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

Create the following urlManager rules in /protected/config/main.php:

<?php
$config = array(
'components' => array(
'urlManager' => array(
'urlFormat' => 'path',
'showScriptName' => false,
'rules' => array(
//admin rules
'admin/<module:\w+>/<action:\w+>/<id:\d+>' => '<module>/admin/<action>',
'admin/<module:\w+>/<action:\w+>' => '<module>/admin/<action>',
'admin/<module:\w+>' => '<module>/admin',
),
),
);

In /protected/modules/user/controllers/DefaultController.php have something like:

<?php
class DefaultController extends Controller {

public function actionIndex() {
$this->render('index');
}

public function actionCreate() {
die('this is default create');
}

public function actionEdit($id) {
die('this is default edit = '.$id);
}

}

Create a /protected/modules/user/config directory and add a main.php file with something like:

<?php
$module_name = basename(dirname(dirname(__FILE__)));
$default_controller = 'default';

return array(
'import' => array(
'application.modules.' . $module_name . '.models.*',
),

'modules' => array(
$module_name => array(
'defaultController' => $default_controller,
),
),

'components' => array(
'urlManager' => array(
'rules' => array(
$module_name . '/<action:\w+>/<id:\d+>' => $module_name . '/' . $default_controller . '/<action>',
$module_name . '/<action:\w+>' => $module_name . '/' . $default_controller . '/<action>',
),
),
),
);

Modules are useful in several scenarios. For a large-scale application, we may divide it into several modules, each being developed and maintained separately. Some commonly used features, such as user management, comment management, may be developed in terms of modules so that they can be reused easily in future projects.

Courtesy: yiiframework.com

Know More About This Topic from our Techies

Latest Post