1

I'm new to magento 2 and I'm trying to understand how exactly injections work in magento.

I understand that injecting a model and interfaces is the right approach in magento 2.

But for some reason when I am trying to inject a model/interface, it throws me and error where as when I use objectManager to get an instance of it, it would work.

For example the below code throws me errors as soon as I inject the eav model or any customer related models or interface.

I was wondering if anyone could elaborate the reason or guide me in the right direction.

public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Eav\Model\Entity $entity
    ) {
        $this->_eavEntity = $entity;
        parent::__construct($context);
    }
2
  • It sounds like you are in production or default mode. You need to be in developer mode. Also, Magento 2's coding standards call for no longer using underscoe in property names, such as $this->_eavEntity`. Commented Jun 24, 2018 at 13:03
  • Thank you I changed the property names.I am in developer mode. I was wondering if there is anything else that we need to make sure when we are injecting something. still throws the error
    – Neha
    Commented Jun 24, 2018 at 13:14

1 Answer 1

2

The first thing to do is switch into developer mode with php bin/magento deploy:mode:set developer

Then delete the directories generated/code and var/cache. In developer mode, interceptor classes, which extend your class, are created on the fly and they live inside of the generated/code directory. Those classes call their parent's constructor, which is the actual constructor in your class. When in production mode, since those files are not created on the fly, you will receive an error because the interceptor class has not been regenerated to reflect your class' custom constructor.

It would also be helpful for you to do the following: php bin/magento cache:clean php bin/magento cache:disable block_html full_page

One thing you will notice as you develop on Magento 2, is that your custom class is not instantiated directly. Instead, the Interceptor class for your class is instantiated.

To test this, use the object manager to call your class. get_class($objectManager->create(\My\Custom\Class::class)). You will notice that the call to get_class returns \My\Custom\Class\Interceptor. If you go ahead and locate the file that contains that class, within the generated/code directory, you will be able to see why you get an error.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.