How to instantiate a model in magento2?
Magento strictly discourages the use of ObjectManager directly. It provides service classes that abstract it away for all scenarios.
For all non-injectables (models) you have to use factory:
protected $pageFactory; public function __construct(\Magento\Cms\Model\PageFactory $pageFactory) { $this->pageFactory = $pageFactory; } public function someFunc() { ... $page = $this->pageFactory->create(); ... }
All you have to do is to ask factory of desired model in constructor. It will be automatically generated when you run Magento or compiler.
You can do it like this:
$model = $this->_objectManager->create('Full\Model\Class\Name\Here');
but you have to make sure that the _objectManager
member exists.
In most of the classes it should, but if it doesn't inject it in the constructor. Like this:
protected $_objectManager;
public function __construct(
...,
\Magento\Framework\ObjectManager $objectManager,
....
){
....
$this->_objectManager= $objectManager;
....
}
[edit one year later]
Even if the answer above works, it is not the best practice. For the right way of doing it see Anton's answer.
Technically if you have an instance of the \Magento\Framework\ObjectManager
you can call create
of get
and this will give you the object you desire. But it really depends on where you want to use this for as Magento 2 shifts towards dependency injection via constructor.