【问题标题】:Include helper class in view在视图中包含帮助程序类
【发布时间】:2018-11-06 23:27:06
【问题描述】:

我正在制定一项要求,即我必须将在我的视图中使用的所有常用方法(如分页等)包含到我的所有视图中。为此,我认为帮助文件很有用,并在 common\helpers\ 目录中创建了帮助文件,名称为 Common 作为帮助文件名。我在视图文件中使用此帮助文件时遇到了困难。

我已将此帮助文件包含在我的视图中

use common\helpers\Common;

当我打开页面时我收到“找不到类'common\helpers\Common'”的错误

我的帮助文件:Common.php

namespace common\helpers;
class Common
{
  protected $_file;
  protected $_data = array();

  public function __construct($file)
  {
    $this->_file = $file;
  }
  public static function getCommonHtml($id=NULL)
  {
   ----
   ----
  }
  -----
  --- Some other methods---
  -----
}

我用谷歌搜索了这个并得到了一些解决方案,但它们从未奏效。

【问题讨论】:

  • common 命名空间中还有其他类吗?他们工作了吗?
  • 不,这是我创建的第一个助手类
  • 保留字可以通用吗?
  • 会不会是你的文件夹被命名为'helper'?有几次这个问题...

标签: yii2 helper autoload


【解决方案1】:

您需要在composer.json 中声明您的新命名空间:

"autoload": {
    "psr-4": {
        ...
        "common\\": "common/"
    }
},

然后运行:

composer dump-autoload

或者你可以为新的命名空间声明别名,所以 Yii 自动加载器会处理它(就像在 advanced template 中一样):

Yii::setAlias('@common', dirname(__DIR__))

但是 Yii 自动加载器将在 Yii 2.1 中被删除,所以我会坚持作曲家方式(或者两者都做 - 别名可能不仅对自动加载有用)。

【讨论】:

  • 我尝试了您的解决方案,我已将您的代码添加到我的 composer.json 并运行命令 composer dump-autoload 但它显示异常为 "[Seld\JsonLint\ParsingException] "./composer.json" does not contain valid JSON Parse error on Line 80"
  • 您的composer.json 中有语法错误。您可以使用jsonlint.com 来验证其内容。顺便说一句:确保从 json 中删除这三个点 - 这只是如何将其添加到现有自动加载规则的示例。
猜你喜欢
  • 2011-05-16
  • 2011-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-12
  • 2010-12-20
  • 2011-04-26
  • 2012-06-29
相关资源
最近更新 更多