Yii 多應用多模塊

本文以YII 2.0.7爲例。php

概述

首先看看多應用和多模塊的特色:html

多應用的特色:git

  • 獨立配置文件
  • 獨立域名

多模塊的特色:github

  • 統一配置文件
  • 統一域名

那麼,實際該怎麼決定使用多應用仍是多模塊呢?web

  • 對於先後臺分離,例如後臺須要單獨的域名進行管理這個應該用多應用
  • 多應用的配置徹底不同,用多應用比較方便,配置文件使用不一樣的
  • 多應用須要更多的域名配置,比價麻煩,對於小項目也不區分域名,多模塊比較好

多應用

最簡單的方法是下載官網的 Yii2的高級應用程序模板:yii-advanced-app-2.0.12.tgz。下載下來解壓後,進入advanced目錄,運行:瀏覽器

# Windows
init.bat

# Linux
init

會在frontendbackend兩個應用的web目錄生成入口文件index.phpfrontendbackend分別表示前臺和後臺應用,裏面的目錄結構是同樣的: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/...

歡迎關注公衆號及時獲取最新文章推送!
clipboard.png

相關文章
相關標籤/搜索