欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

Yii 框架学习--03 多应用多模块

发布时间:2025/6/15 编程问答 43 豆豆
生活随笔 收集整理的这篇文章主要介绍了 Yii 框架学习--03 多应用多模块 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

本文以YII 2.0.7为例。

概述

首先看看多应用和多模块的特点:

多应用的特点:

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

多模块的特点:

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

那么,实际该怎么决定使用多应用还是多模块呢?

  • 对于前后台分离,例如后台需要单独的域名进行管理这个应该用多应用
  • 多应用的配置完全不一样,用多应用比较方便,配置文件使用不同的
  • 多应用需要更多的域名配置,比价麻烦,对于小项目也不区分域名,多模块比较好

多应用

最简单的方法是下载官网的 Yii2的高级应用程序模板:yii-advanced-app-2.0.12.tgz。下载下来解压后,进入advanced目录,运行:

# Windows init.bat# Linux init

会在frontend和backend两个应用的web目录生成入口文件index.php。frontend和backend分别表示前台和后台应用,里面的目录结构是一样的:

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

转载于:https://www.cnblogs.com/52fhy/p/7401625.html

总结

以上是生活随笔为你收集整理的Yii 框架学习--03 多应用多模块的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。