本文以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/...
歡迎關注公衆號及時獲取最新文章推送!