YII2框架学习 扩展篇(一) 模块化设计

来源:互联网 发布:ug nx8.0数控编程教程 编辑:程序博客网 时间:2024/06/01 08:59

模块化设计是指把一个系统分成若干个子模块,组合完成系统设计。比如讲一个博客系统分成:用户管理模块;文章管理模块;评论模块;广告模块。而子模块又可以继续细分,比如用户模块可以划分为:密码管理模块,用户信息模块等等。 细分子模块时,应该有一个配置文件控制各个子模块的开启。

接下来学习YII框架的模块化设计,首先要打开gii工具,http://localhost/basic/web/index.php?r=gii。进到Module Generator,填入Module Class和id.


然后在框架目录就会多出来这个子模块,真是太方便了。


包含控制器文件夹,视图文件夹和模块的类。

生成的时候可以多加一层路径,这样可以生成多个子模块也不会互相干扰


要想使子模块生效,需要修改basic\config\web.php,在config数组插入

'modules' => [        'comment' => [            'class' => 'app\modules\comment\Comment',        ],    ],
使用子模块有两种方式:

第一种,父模块调用

只要在父模块控制器写入

 //获取子模块        $comment = \YII::$app->getModule('comment');        //调用子模块        $comment->runAction('default/index');

就可以调用了。

第二种,直接url访问子模块

http://localhost/basic/web/index.php?r=comment/default/index


前面提到了子模块可以继续细分模块,现在来试一试



可以看到孙模块生成成功了


到他的父模块comment配置信息,修改父模块的类文件,Comment.php

<?phpnamespace app\modules\comment;/** * comment module definition class */class Comment extends \yii\base\Module{    /**     * @inheritdoc     */    public $controllerNamespace = 'app\modules\comment\controllers';    /**     * @inheritdoc     */    public function init()    {        parent::init();                $this->modules = ['modules' => [            'comment2' => [                'class' => 'app\modules\comment\modules\comment2\Comment2',            ],        ],];        // custom initialization code goes here    }}
配置就完成了。通过子模块调用孙模块,再访问子模块就可以实现孙模块了,我直接通过urlhttp://localhost/basic/web/index.php?r=comment/comment2/default/index访问孙模块失败了,不知道为什么,知道的留言告诉我谢谢。

原创粉丝点击