2

I am trying to load Magento\Customer\Api\Data\CustomerExtensionFactory in a plugin using the ObjectManager injected in the Plugin constructor. The file var\generation\Magento\Customer\Api\Data\CustomerExtensionFactory.php does exist. When I run $this->customerExtensionFactory = $objectManager->get(self::CUSTOMER_EXTENSION_FACTORY_PATH); in my Plugin it throws an error: "Notice: Undefined index: instance in \/vagrant\/data\/magento2\/lib\/internal\/Magento\/Framework\/ObjectManager\/Factory\/AbstractFactory.php on line 222"

My Plugin code is this:

<?php namespace My\Module\Model\Plugin\Card; use Magento\Customer\Api\Data\CustomerExtensionFactory; use Magento\Customer\Model\Customer; use Magento\Framework\ObjectManager\ObjectManager; class MyPlugin { const CUSTOMER_EXTENSION_FACTORY_PATH = 'Magento\Customer\Api\Data\CustomerExtensionFactory'; /** * @var \Magento\Customer\Api\Data\CustomerExtensionFactory */ protected $customerExtensionFactory; public function __construct(ObjectManager $objectManager) { /** * @var \Magento\Customer\Api\Data\CustomerExtensionFactory */ $this->customerExtensionFactory = $objectManager->get(self::CUSTOMER_EXTENSION_FACTORY_PATH); } public function afterGetDataModel(Customer $customer, $customerDataObject) { $extension = $this->customerExtensionFactory->create()->setOpenpayCard('aaa-123'); $customerDataObject->setExtensionAttributes($extension); return $customerDataObject; } } 

Any ideas on what that may be?

1 Answer 1

3

You do not need ObjectManager. Here is a reworked version:

<?php namespace My\Module\Model\Plugin\Card; use Magento\Customer\Api\Data\CustomerExtensionFactory; use Magento\Customer\Model\Customer; class MyPlugin { /** * @var \Magento\Customer\Api\Data\CustomerExtensionFactory */ protected $customerExtensionFactory; /** * @param \Magento\Customer\Api\Data\CustomerExtensionFactory $customerExtensionFactory */ public function __construct(CustomerExtensionFactory $customerExtensionFactory) { $this->customerExtensionFactory = $customerExtensionFactory; } public function afterGetDataModel(Customer $customer, $customerDataObject) { $extension = $this->customerExtensionFactory->create()->setOpenpayCard('aaa-123'); $customerDataObject->setExtensionAttributes($extension); return $customerDataObject; } } 
2
  • Right! I actually did this and it worked. I did not know how DI worked in the Plugins. Is there other way to inject objects other than annotations? Commented Dec 8, 2015 at 20:14
  • Here are more details about DI in magento2 devdocs.magento.com/guides/v2.0/extension-dev-guide/… Commented Dec 8, 2015 at 20:18

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.