Support & Downloads

Quisque actraqum nunc no dolor sit ametaugue dolor. Lorem ipsum dolor sit amet, consyect etur adipiscing elit.

s f

Contact Info
198 West 21th Street, Suite 721
New York, NY 10010
[email protected]
+88 (0) 101 0000 000
margnto2

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.

Sagar Doshi

CEO / Managing Partner

[email protected]

Post a Comment