0

I want to use below code in Magento 2 constructor.

$stockItem = $objectManager->create('Magento\CatalogInventory\Model\Stock\Item');

Can any one tell me the right way of calling above create class into constructor as a dependency class?

3
protected $stockItemFactory;
public function __construct(
    ...
    \Magento\CatalogInventory\Model\Stock\ItemFactory $stockItemFactory,
    ....
) {
    ....
    $this->stockItemFactory = $stockItemFactory;
    ....
}

Then you can use in your class

$stockItem = $this->stockItemFactory->create();
| improve this answer | |
  • Thanks +1 @ Marius. In same scenario, how get ($objectManager->get('Magento\CatalogInventory\Model\Stock\Item');) can be converted in to dependency calss. – Krishna ijjada Oct 17 '16 at 12:02
  • The stock item instance is non injectable. I mean, it is, but you should not inject that directly. You may end up with problems if you do. Instead you should inject the stock item factory class and create the stock item instance when you need it. – Marius Oct 17 '16 at 12:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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