Question

Just when I think I grasp the Magento 2 object manager and dependency injection something happens which I don't understand. I think I am passing context en pagefactory objects but Magento says I am not. The second one seems wrong.

Recoverable Error: Argument 2 passed to Demo\Hello\Controller\Adminhtml\Order\MassPrint::__construct() must be an instance of Magento\Framework\View\Result\PageFactory, instance of Magento\Framework\App\ResourceConnection given, called in 

The controller:

<?php 
namespace Demo\Hello\Controller\Adminhtml\Order;

use Magento\Backend\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;

class MassPrint extends \Magento\Backend\App\Action {

  public function __construct(Context $context, PageFactory $pageFactory) {
    parent::__construct($context);
  }

}

It understands the type hinting like I want:

must be an instance of Magento\Framework\View\Result\PageFactory

But it is passing

instance of Magento\Framework\App\ResourceConnection given

Why is this? There is some magic going on with Magento which I don't understand (yet).

Was it helpful?

Solution

TL;DR

If you see a an error with Interceptor.php be sure to empty /var/generation/ before you look further. It will save you lots of time.

Explanation

After some testing I found the underlying cause. When executing a custom controller for the first time Magento automatically generates files. So far so good. In my case just one. It's living in var\generation\ The full path in this example would be var\generation\Demo\Hello\Controller\Adminhtml\Order\MassPrint\Interceptor.php.

This class is extending your custom controller. So naturally it is calling the parent constuctor in its own constuctor. So if you make changes to your controller constructor this file must be regenerated to mach your new code. If you don't it will yield unwanted results. So be sure to at least delete the Interceptor class for that controller. Easier would be to empty the whole director so Magento will regenerate all files matching your new code.

rm -rf var/generation/*

Actually magento gives a very good clue where to look in the last part of the error message.

called in /var/generation/Demo/Hello/Controller/Adminhtml/Order/MassPrint/Interceptor.php on line 15
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top