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.
1 2 3 4 5 6 7 8 9 10 |
<?php $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory'); $productCollection->addAttributeToSelect('*'); $productCollection->load(); foreach ($productCollection as $product) { echo "<pre>"; print_r($product->getData()); } |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php namespace Codextblog\Pcollection\Block\Index; class Index extends \Magento\Framework\View\Element\Template { protected $_productCollectionFactory; public function __construct( \Magento\Backend\Block\Template\Context $context, \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory, array $data = [] ) { $this->_productCollectionFactory = $productCollectionFactory; parent::__construct($context, $data); } public function getProductCollection() { $collection = $this->_productCollectionFactory->create(); $collection->addAttributeToSelect('*'); return $collection; } } |
Step 2: Call getProductCollection in your phtml file
For example our phtml file Index.phtml is under app/code/Codextblog/Pcollection/view/frontend/templates
1 2 3 4 5 6 7 |
<?php $pCollection = $block->getProductCollection(); foreach ($pCollection as $product) { echo "<pre>"; print_r($product->getData()); } |
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.