本文以YII 2.0.7為例,給大家分享了關於Yii多應用多模組,有需要的朋友可以參考一下
概述
首先看看多應用和多模組的特點:
多應用的特點:
多模組的特點:
那麼,實際該怎麼決定使用多應用還是多模組呢?
對於前後台分離,例如後台需要單獨的網域名稱進行管理這個應該用多應用
多應用的配置完全不一樣,用多應用比較方便,設定檔使用不同的
多應用需要更多的網域名稱配置,比價麻煩,對於小項目也不區分網域名稱,多模組比較好
多應用
最簡單的方法是下載官網的 Yii2的進階應用程式程式模板:yii-advanced-app-2.0.12.tgz。下載下來解壓後,進入advanced目錄,運行:
# Windowsinit.bat# Linuxinit
會在frontend和backend兩個應用的web目錄產生入口檔案index.php。frontend和backend分別表示前台和後台應用,裡面的目錄結構是一樣的:
assets/ config/ controllers/ models/ runtime/ views/ web/
運行:
$ cd advanced/frontend/web$ php -S 0.0.0.0:8888PHP 5.6.22 Development Server started at Sun Aug 20 21:10:28 2017Listening on http://0.0.0.0:8888
開啟瀏覽器輸入http://0.0.0.0:8888就可以訪問預設的首頁了。
建議model還是放在根目錄的common/models裡。
多模組
多模組可以參照http://www.yiichina.com/doc/g...。樣本:在frontend裡建立一個h5應用:
1、建立相關目錄
$ cd frontend$ mkdir -p modules/h5 && cd modules/h5$ mkdir controllers$ touch Module.php
2、Module.php內容樣本:
<?phpnamespace frontend\modules\h5;class Module extends \yii\base\Module{ public function init() { parent::init(); $this->params['foo'] = 'bar'; // ... 其他初始化代碼 ... }}
3、在frontend/config/main.php增加模組的申明:
'modules' => [ 'h5' => [ 'class' => 'frontend\modules\h5\Module', // ... 模組其他配置 ... ],],
4、在modules/h5/controllers建立控制器類:
<?phpnamespace 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/indexr=v2/site/index
原載於:http://www.cnblogs.com/52fhy/...