1) 打开 Gii 代码生成工具,进入 Module Generator 页面,输入模块名如 test ,点击生成;
2) 生成的代码在 protected/modules/test 目录下 , 生成的文件如下:
test/TestModule.php ---- 模块主类,继承自 CWebModule
test/controllers/DefaultController.php ----- 默认 Controller, 里面有一个 index action , action 跳转到 index 视图;该模块的 Controller 都放在这个目录下
test/views/default/index.php --- 这是 DefaultController 的视图文件,对应 index action ;所有 DefaultController 的 action 的视图文件都放在这里;
3) 配置模块
在 config/main.php 里的 modules 中加入该模块:
'modules'=>array(
'main',
'admin',
'test',
),
4) 在模块初始化函数中设置默认项:打开 TestModule.php, 在 init 方法中加入:
Yii::app()->errorHandler->errorAction = 'test/default/error';
Yii::app()->defaultController = 'test/default';
Yii::app()->user->loginUrl = 'test/default/login';
请确保这些 action 和 controller 都已经实现。
5) 打开浏览器,访问: 即可访问到默认的首页,这个首页是默认 Controller DefaultController 里的默认 Index action 跳转到的 default/index.php 的视图。
6) Yii 的模块中,所有 Controller 全部放在 conroller 目录下,每一个 controller 都对应一个目录,目录位于 views 下,里面存放该 controller 所有 action 对应的 view 。一般来讲,一个独立 action 都会对应一个 view 。
7) 加入需要添加模块独有的 model 和 component ,则都加在 test/models 和 test/components 目录下,在 TestModule 模块类中会自动将他们引入:
$this->setImport(array(
'test.models.*',
'test.components.*',
));
8) 需要添加模块独有的 layout ,请加到 test/views/layouts 目录下,使用该 layout 时使用: /layouts/layoutName 来调用, layout 可以嵌套,父 layout 用 <?php echo $content; ?> 来为子 layout 占位,子 layout 内容包含在以下语句中,其中指定父 layout :
<?php $this->beginContent('/layouts/main'); ?>
<?php $this->endContent(); ?>
9) 在 Controller 中指定该 Controller 所有 action 默认使用的 layout
在 Controller 类中定义以下变量,以覆盖父类中的默认值:
public $layout='/layouts/main';
public $defaultAction='index';
如果要是有网站根目录下的 layout ,需要将目录的 / 换成 //.