14

Is there a way of doing something simple as in magento2?

call function like this in magento 2,

$model = Mage::getModel('cms/page');
  • question is not clear put more details.... – Amit Bera Aug 20 '14 at 14:42
28

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.

11

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.

  • got error - Class Magento\Framework\ObjectManager does not exist – Anas Mansuri Aug 14 at 7:27
5

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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