Take the 2-minute tour ×
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It's 100% free, no registration required.

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

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

3 Answers 3

up vote 2 down vote accepted

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;
    ....
}
share|improve this 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.

share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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