【发布时间】:2014-10-06 01:13:49
【问题描述】:
我想创建一个这样的目录树:
- 型号
- 模块
- 帮助
- 控制器
- 默认
- IndexAction.php
- DefaultController.php
- 默认
- 查看次数
- 默认
- index.php
- 默认
- help.php
- 控制器
- 帮助
所以如果我调用 localhost/mysite/web/index.php?r=help/default/index 我应该得到索引视图。
所以我用 gii 创建了一个模块。我的模块类是“app\modules\help\help”。我不得不两次使用帮助,以便将我的模块放在子目录中。 (这是我没有得到的东西。为什么不为 Yii 为每个模块创建一个子目录?)
在下一步中,我创建了独立操作
<?php
namespace app\modules\help\controllers;
use yii\base\Action;
class IndexAction extends Action
{
public function run()
{
$this->controller->render('index');
}
}
在下一步中,我修改了我的控制器以使用独立操作
<?php
namespace app\modules\help\controllers;
use yii\web\Controller;
class DefaultController extends Controller
{
public function actions()
{
return [
'index' => 'app\modules\help\controllers\default\IndexAction',
];
}
}
如果我现在在浏览器中调用我的视图,我会收到以下错误:
Unknown Class – yii\base\UnknownClassException
Unable to find 'app\modules\help\controllers\default\IndexAction' in file: E:\wamp\www\my_website/modules/help/controllers/default/IndexAction.php. Namespace missing?
但是如果我在我的电脑上转到这个路径 E:\wamp\www\my_website/modules/help/controllers/default/ 我会看到 IndexAction.php 有人能帮我吗?
独立操作位于控制器的子目录中。所以命名空间应该是
namespace app\modules\help\controllers\default;
但这会导致这个错误:
PHP Parse Error – yii\base\ErrorException
syntax error, unexpected 'default' (T_DEFAULT), expecting identifier (T_STRING)
编辑
如果我在 IndexAction.php 中使用此命名空间 app\modules\help\controllers\IndexAction,则会收到以下错误。即使我更改控制器中的路由,我也会得到 unknownClassException:
Unknown Class – yii\base\UnknownClassException
Unable to find 'app\modules\help\controllers\default\IndexAction' in file: E:\wamp\www\my_website/modules/help/controllers/default/IndexAction.php. Namespace missing?
如果我在 IndexAction.php 中使用这个命名空间 app\modules\help\controllers\default 我会得到:
PHP Parse Error – yii\base\ErrorException
syntax error, unexpected 'default' (T_DEFAULT), expecting identifier (T_STRING)
【问题讨论】:
-
你试过
app\modules\help\controllers\IndexAction吗?或将操作的命名空间更改为app\modules\help\controllers\default -
答案显示在 EDIT 语句的上方代码中
-
您编辑的第二部分是正确的方法。错误来自
default是保留关键字(switch语句的一部分)这一事实。如果您将它(和文件夹名称)更改为其他名称,它应该可以工作。 -
你是对的。如果我将默认值重命名为 index,它会起作用。
标签: php yii namespaces action yii2