How to Instantiate a Model in Magento 2

We all know that in Magento 1 We can easily instantiate model using Mage::getModel and Mage::getSingleton methods. But instantiate a model in Magento 2 something different.

In Magento 2 we can instantiate a model using Object Manager. Yes, you heard it correctly, ObjectManager is a replacement for getModel and getSingleton Method.

There are two approaches you can invoke ObjectManager in Magento 2 to instantiate a model or to get the model collection.

Approach 1: Using ObjectManager Directly anywhere

Let’s say we want to get product collection in our Magento 2 custom module phtml file. You can get this using below code.

Approach 2: Inject model into Constructor and instantiate

Second and recommended approach of instantiating a model in Magento 2 is using a constructor. To get product collection in your custom phtml file, You need to create a block file inject the product model into the constructor of that block file.
 
Step 1: Create Block.php file
For example our block file Index.php is under app/code/Codextblog/Pcollection/Block/Index

Step 2: Call getProductCollection in your phtml file
For example our phtml file Index.phtml is under app/code/Codextblog/Pcollection/view/frontend/templates

This is how you can get product collection in your custom phtml file.
 

Which Approach to use?

Well, it is a very tedious task to go with approach 2 to just get product collection. But as per Magento Official doc, you should always use constructor method to instantiate a model in Magento 2 to maintain the implementation of Dependency Injection.

Default image
Sagar Doshi
CEO / Managing Partner

An expert in his field, Sagar Doshi is the CEO and team leader in

meghrajtechnosoft.

His passion for Magento has inspired others in the team too. Apart from work, he is a cricket lover."

Articles: 25

Leave a Reply