我有一个相当大的 Yii1 应用程序,我想慢慢迁移到 Yii2。我想逐步做到这一点。
我已按照 Yii2 and Yii1 integration manual 中的说明进行操作.
我的应用程序运行良好。
我也试过yii2-yii-bridge技巧,经过一些调整,它似乎也可以工作。
我的问题是,既然我知道我的应用程序中有两个版本的 Yii,我该如何开始添加 Yii2 风格的 Controller ?
如果我创建一个简单的 Yii2 样式 Controller ,如下所示:
namespace app\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
class SecondController extends Controller {
public function behaviors()
{
return [
'access' => [
'class' => \yii\filters\AccessControl::className(),
'only' => ['index'],
'rules' => [
// allow authenticated users
[
'allow' => true,
'roles' => ['@'],
],
// everything else is denied
],
],
];
}
public function actionIndex()
{
Yii::trace("(!!!) SecondController::index called!!!");
return "SecondController::index!!";
}
} // class
我无法使用我习惯的 URL 方案访问它,所以 http://local.url/second/index似乎没有找到。
但是,如果我按照我一直做的方式创建 Yii1 样式,它就可以很好地解决:
class ThirdController extends Controller {
public function accessRules() {
return array(
array('allow',
'actions' => array('index'),
'users' => array('*'),
),
);
}
public function actionIndex() {
Yii::trace("ThirdController::index called!!!");
return "ThirdController::index!!";
}
}
似乎
<controller>/<action>
的默认 url 映射无法处理命名空间 Controller 有没有办法解决这个问题?
最佳答案
Seems that the default url mapping of / cannot deal with namespaced controllers is there a way around this?
要支持命名空间 Controller ,您需要使用
CWebModule::$controllerNamespace
用于模块 Controller 或 CWebApplication::$controllerNamespace
用于全局应用程序 Controller 。然后给定范围内的所有 Controller 都需要命名空间。如果您只想在某些 Controller 中使用命名空间,则需要使用 CWebApplication::$controllerMap
或 CWebModule::$controllerMap
并为指定的路由配置 Controller 类。然而,在 Yii 1.1 应用程序中运行 Yii 2.0 Controller 很可能根本不起作用。如果您只想将应用程序的一部分移动到 Yii 2,我建议将其配置为单独的应用程序并运行,并使用重写规则路由到正确的应用程序。例如,如果您移动
user
Yii 2 的模块你可以在你的 .htaccess
中使用它:RewriteEngine on
# Yii 2 rules
RewriteRule ^user index-yii2.php [L]
# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# otherwise forward it to index.php
RewriteRule . index.php [L]
在
index.php
你应该在 Yii 1.1 和 index-yii2.php
中引导你的应用程序的文件。你有 Yii 2 应用程序。
关于yii - Yii2 Controller 与 Yii1 Controller 的结合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37351722/