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

时间:2016-11-29 13:45:53

标签: magento magento2

首先,我对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 :(得分:0)

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

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

一点点帮助本来不错,Magento!可能是错误报告未找到所请求的类?不过,至少这终于结束了。