Question

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?

Was it helpful?

Solution

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();
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top