本文以YII 2.0.7为例。php
首先看看多应用和多模块的特色:html
多应用的特色:git
多模块的特色:github
那么,实际该怎么决定使用多应用仍是多模块呢?web
最简单的方法是下载官网的 Yii2的高级应用程序模板:yii-advanced-app-2.0.12.tgz。下载下来解压后,进入advanced
目录,运行:浏览器
# Windows init.bat # Linux init
会在frontend
和backend
两个应用的web
目录生成入口文件index.php
。frontend
和backend
分别表示前台和后台应用,里面的目录结构是同样的:yii2
assets/ config/ controllers/ models/ runtime/ views/ web/
运行:app
$ cd advanced/frontend/web $ php -S 0.0.0.0:8888 PHP 5.6.22 Development Server started at Sun Aug 20 21:10:28 2017 Listening on http://0.0.0.0:8888
打开浏览器输入http://0.0.0.0:8888就能够访问默认的首页了。frontend
建议model仍是放在根目录的common/models
里。yii
多模块能够参照http://www.yiichina.com/doc/g...。示例:在frontend
里新建一个h5
应用:
一、创建相关目录
$ cd frontend $ mkdir -p modules/h5 && cd modules/h5 $ mkdir controllers $ touch Module.php
二、Module.php
内容示例:
<?php namespace frontend\modules\h5; class Module extends \yii\base\Module { public function init() { parent::init(); $this->params['foo'] = 'bar'; // ... 其余初始化代码 ... } }
三、在frontend/config/main.php
增长模块的申明:
'modules' => [ 'h5' => [ 'class' => 'frontend\modules\h5\Module', // ... 模块其余配置 ... ], ],
四、在modules/h5/controllers
新建控制器类:
<?php namespace frontend\modules\h5\controllers; use Yii; use common\models\LoginForm; use frontend\models\SignupForm; use frontend\models\ContactForm; use yii\base\InvalidParamException; use yii\web\BadRequestHttpException; use yii\web\Controller; class SiteController extends Controller { public function actionIndex() { return "hello h5 module"; //return $this->render('index'); } }
浏览器访问:http://localhost:8888/index.php?r=h5/site/index
便可访问。
还有一种方法也能够实现相似该URL路由的访问形式,例如r=test/site/index
。只须要在frontend/controllers
目录新建个子目录叫test
,把控制器放在里面,而后改下命名空间为
namespace frontend\controllers\test;
就能够了。这种能够用于API版本控制,例如:
r=v1/site/index r=v2/site/index
原载于:http://www.cnblogs.com/52fhy/...
欢迎关注公众号及时获取最新文章推送!