需求:浏览器访问 reports/daily
时,使其默认转到 v1 版本,若 URL 参数带有版本参数 version,则转到对应的版本代码。
reports/daily
->modules/reports/controllers/v1/DailyController.php
reports/daily?version=v2
->modules/reports/controllers/v2/DailyController.php
目录结构如下:
vbnet
modules/
├── reports/
│ ├── controllers/
│ │ ├── v1/
│ │ │ └── DailyController.php
│ │ └── v2/
│ │ └── DailyController.php
│ └── views/
│ ├── v1/
│ │ └── daily/
│ │ └── index.php
│ └── v2/
│ └── daily/
│ └── index.php
└── Module.php
首先,修改 Module.php
文件,在模块初始化时从 URL 中解析 version 参数
php
// Module.php
public function init()
{
parent::init();
$version = $this->getVersionFromQueryString();
// 修改命名空间
$this->controllerNamespace = sprintf('app\modules\reports\controllers\%s', $version);
}
protected function getVersionFromQueryString(): string
{
$request = \Yii::$app->request;
$version = $request->get('version', 'v1');
if (!in_array($version, ['v1', 'v2'])) {
$version = 'v1';
}
return $version;
}
此外,还需重写模块获取视图路径的方法
php
// Module.php
public function getViewPath(): string
{
return $this->basePath . '/views/' . $this->getVersionFromQueryString();
}
若不重写获取视图路径方法,加载视图时需要指定详细路径
$this->render('@reports/views/v1/daily/index')
,非常麻烦!
控制器代码如下
php
// v1/DailyController.php
namespace app\modules\reports\controllers\v1;
use yii\web\Controller;
class DailyController extends Controller
{
public function actionIndex(): string
{
// 只需要 index 即可找到对应控制器的视图
return $this->render('index');
}
}
完工。