首页 文章

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

提问于
浏览
1

首先,我对Magento 2很新,但我已经使用了Magento 1.x一段时间了 .

我已经阅读了很多关于如何解决DI相关问题的内容,但我仍然坚持这一点:

异常#0(异常):可恢复错误:传递给Cefar \ AO \ Helper \ Ao :: __ construct()的参数1必须是Magento \ Framework \ App \ Helper \ Context的实例,Magento \ Framework \ ObjectManager的实例\给定的ObjectManager,在第93行的... / vendor / magento / framework / ObjectManager / Factory / AbstractFactory.php中调用,在第11行的... / Cefar / AO / Helper / Ao.php中定义

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

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

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;
    }
}

这里没什么特别的 . 我很困惑这是怎么发生的;扩展中的每个其他定义的类都正确获取其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 没有一个条目......但是有一些框架类使用ID来导入 Magento\Customer\Model\Session 已经工作了 .

1 回答

  • 0

    长话短说,这是因为一个错字 .

    有时当包含帮助程序时,它被称为 Cefar\AO\Helper\Ao ,其他时候被称为 Cefar\AO\Helper\AO . 本质上,ObjectManager正在解析对同一个类的这两个引用,但它只有一个名称的类型提示,因此它不知道要向不正确的名称提供什么 .

    Magento有点帮助会很好!可能是错误报告未找到所请求的类?不过,至少这终于结束了 .

相关问题