Magento 2.2 Can we use Object Manager in Controller or Block? [duplicate]
-
20-03-2021 - |
Question
To get product data, I am using object manager in my controller, but I read in docs that we should not use it directly.
<?php
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?
Solution
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..!!
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange