文章出處

本文以YII 2.0.7為例。

概述

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

多應用的特點:

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

多模塊的特點:

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

那么,實際該怎么決定使用多應用還是多模塊呢?

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

多應用

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

# Windows
init.bat

# Linux
init

會在frontendbackend兩個應用的web目錄生成入口文件index.phpfrontendbackend分別表示前臺和后臺應用,里面的目錄結構是一樣的:

assets/  
config/  
controllers/  
models/  
runtime/  
views/  
web/

運行:

$ 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就可以訪問默認的首頁了。

建議model還是放在根目錄的common/models里。

多模塊

多模塊可以參照http://www.yiichina.com/doc/guide/2.0/structure-modules配置。示例:在frontend里新建一個h5應用:

1、建立相關目錄

$ cd frontend
$ mkdir -p modules/h5 && cd modules/h5
$ mkdir controllers
$ touch Module.php

2、Module.php內容示例:

<?php
namespace 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新建控制器類:

<?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

文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()