【问题标题】:Yii2: Stand alone Action in ModuleYii2:模块中的独立动作
【发布时间】: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


【解决方案1】:

正如 D.Mill 在他的评论中所说。 default 是保留关键字。我不得不重命名目录,现在它工作得很好。

【讨论】:

    【解决方案2】:

    您使用了错误的命名空间 用这样的东西替换你的代码(注意反斜杠)

        public function actions()
        {
            return [
                'index'    => '\app\modules\help\controllers\default\IndexAction',
            ];
        }
    

    【讨论】:

    • 即使我使用前导反斜杠也不起作用。我认为错误消息中的斜杠是前斜杠和反斜杠是由 WAMP 引起的。
    • 这不起作用意味着,我得到了一个 UnknownClassException,就像我的问题所示
    猜你喜欢
    • 1970-01-01
    • 2012-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多