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..!!