To get product data, I am using object manager in my controller, but I read in docs that we should not use it directly.

 pubic function execute()
     $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
     $id = '10';
     $product = $objectManager->create('Magento\Catalog\Model\Product')-load($id);
     // My code here

Please suggest me a way how to use Object Manager in controller or block?


You should not use the ObjectManager directly!

Exception from the rule are:

  • in static magic methods like __wakeup, serialize, etc
  • in case you should make backward compatibility of constructor
  • in global scope, like in fixtures of integration test.
  • in class that needs only for creation of object like factory, proxy , etc.

You could use it in Factories, but except that you should inject the Object Manager in the Constructor first then you can use its object in your method:

Step 1: declare private object:

private $_objectManager;

Step 2: inject in the constructor and initialize it:

public function __construct(
    \Magento\Framework\ObjectManagerInterface $objectmanager,
) {
    $this->_objectManager = $objectmanager;

Step 3: use in your execute/any method:

    public function create() 
        $id = '10';
        $product = $this->_objectManager->create('\Magento\Catalog\Model\Product')-load($id);

Hope it helps..!!

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