7

I want to use an instance of a Model into a Block.

in Magento 1 they uses:

$exple = Mage::getModel('exple/standard');

How can I do this with Magento 2?

Sabri Tahri
  • 327
  • 2
  • 6
  • 9

4 Answers4

11

Override constructor in your block class and add your class factory as dependency.

public function __construct(
    \Magento\Backend\Block\Template\Context $context,
    \Vendor\Exple\Model\StandardFactory $modelFactory,
    array $data = []
) {
      $this->modelFactory = $modelFactory;
      parent::__construct($context, $data);
}

function someMetod() {
    $model =  $this->modelFactory->create();
}
KAndy
  • 20,811
  • 3
  • 49
  • 59
  • If I need to use my class factory in many methods of my block, have I to call create() factory method in everywhere? Or should I call I only one time? And in this case, where? – WaPoNe Jan 13 '17 at 09:23
  • How to use it for eav/entity_attribute ? – Jafar Pinjar Aug 04 '18 at 10:56
8

You can instantiate your model by using constructor. You can call it by ObjectManager directly but passing by constructor is the best approach.

Example by using constructor

protected $customer;

/**
 * @param \Magento\Framework\App\Action\Context $context
 * @param \Demo\HelloWorld\Model\Customer $customer
 */
public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Demo\HelloWorld\Model\Customer $customer
) {
    $this->customer = $customer;

    parent::__construct($context);
}

$this->customer is your model instances.

Hope this helps.

Krishna ijjada
  • 8,927
  • 6
  • 41
  • 70
  • Is it a correct way (best practice) in Magento 2 or it should be better to use class factory as dependency as suggested by @KAndy? – WaPoNe Jan 13 '17 at 08:42
5

You can use below code to call the model from anywhere

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$model = $objectManager->create('\Namespace\Modulename\Model\Modelname');
Black
  • 3,310
  • 4
  • 31
  • 110
Jaimin Parikh
  • 2,392
  • 2
  • 13
  • 27
0

Get the instance of a factory for your model using dependency injection. You don't need to define the factory explicitly, because factories are an automatically generated class type. When you reference a factory in a class constructor, Magento’s object manager generates the factory class if it does not exist. https://devdocs.magento.com/guides/v2.3/extension-dev-guide/code-generation.html

public function __construct(
    \Magento\Backend\Block\Template\Context $context,
    \Helloworld\News\Model\NewsFactory $newsFactory,
    array $data = []
) {
    $this->newsFactory = $newsFactory;
    parent::__construct($context, $data);
}

Calling the create() method on a factory gives you an instance of its specific class.

$model = $this->newsFactory->create();
marco-s
  • 101