Magento2:参数 1 [...] 必须是 Magento\Framework\App\Helper\Context 的实例

Magento2: Argument 1 [...] must be an instance of Magento\Framework\App\Helper\Context

首先,我是 Magento 2 的新手,但我已经使用 Magento 1.x 一段时间了。

我已经阅读了很多关于如何解决与 DI 相关的问题,但我仍然停留在这个问题上:

Exception #0 (Exception): Recoverable Error: Argument 1 passed to Cefar\AO\Helper\Ao::__construct() must be an instance of Magento\Framework\App\Helper\Context, instance of Magento\Framework\ObjectManager\ObjectManager given, called in .../vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php on line 93 and defined in .../Cefar/AO/Helper/Ao.php on line 11

许多其他答案建议删除 var/di 和 var/generation 文件夹,有时也会删除 var/cache。虽然这解决了问题,但在 bin/magento setup:di:compile 为 运行 时再次出现,这意味着代码无法在生产环境中使用。

我检查过 Ao class 没有实例化任何对象。它也不会尝试重新制作任何可以由给定上下文提供的对象。这是代码:

namespace Cefar\AO\Helper;

class Ao extends \Magento\Framework\App\Helper\AbstractHelper
{
    const DEFAULT_GRID_COLS = 4;

    protected $_session;

    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Customer\Model\Session $session
    )
    {
        parent::__construct($context);
        $this->_session = $session;
    }

    public function getConfig($path)
    {
        return $this->scopeConfig->getValue($path);
    }

    public function isActive($url = null, $print = true) {
        $active = ($url && strstr($_SERVER['REQUEST_URI'], $url) !== false);

        if ($active && $print) {
            echo "active";
        } else {
            return $active;
        }
    }

    public function isLoggedIn()
    {
        return $this->_session->isLoggedIn();
    }

    public function limitWords($text = '', $limit = 10, $showDots = true)
    {
        $words = explode(' ', $text);
        $limited = array_slice($words, 0, $limit);
        $newText = implode(' ', $limited);

        if (count($words) > $limit && $showDots) {
            $newText .= '...';
        }

        return $newText;
    }

    public function getCurrentGrid()
    {
        return ($this->_getRequest()->getParam('grid'))
            ? $this->_getRequest()->getParam('grid')
            : self::DEFAULT_GRID_COLS;
    }
}

这里没有什么特别的。我对这是怎么发生的感到困惑;扩展中定义的每个其他 class 都正确获取其 DI 参数。为什么 ObjectManager 装置提供不需要的参数?错误报告中给出的相关调用为:

.../vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php(93): Cefar\AO\Helper\Ao->__construct(Object(Magento\Framework\ObjectManager\ObjectManager))

所以它甚至没有提供两个参数!

我也读过有关在 di.xml 中提供类型提示的信息,但它似乎与此处无关,因为这两种类型都是 Magento 库的一部分?我注意到 Magento\Framework\App\Helper\Context 有一个条目,但 Magento\Customer\Model\Session 没有条目...但是有框架 classes 使用 ID 导入 Magento\Customer\Model\Session 已经可以工作了。

长话短说,这是因为打字错误。

有时,当包含助手时,它被称为 Cefar\AO\Helper\Ao,而其他时候,被称为 Cefar\AO\Helper\AO。本质上,ObjectManager 正在将这两个引用解析为相同的 class,但它 只有其中一个名称的类型提示 ,因此它不知道要提供什么给不正确的。

Magento,能有一点帮助就好了!可能是找不到请求的 class 的错误报告?尽管如此,至少这一切终于结束了。