Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magento-when to use Mage::getResourceModel and Mage::getModel

Tags:

magento

I just started to use Magento, and in particular on how models and the ORM work.

I have used these three methods

Mage::getResourceModel() Mage::getModel() Mage::getSingleton() 

Can anyone tell me what the difference is between each of them?

I have found that getSingleton() shares memory while getModel() uses fresh memory for new object for the same table being loaded.

I have used all the methods above but could not differentiate between them and when is appropriate to use which one.

like image 729
user3177068 Avatar asked Jan 16 '14 05:01

user3177068


People also ask

What is Mage :: getModel ()?

Mage::getModel() will create a new instance of an object each time even such object exists in configuration. Example $product1 = Mage::getModel('catalog/product'); $product2 = Mage::getModel('catalog/product'); $product1 and $product2 both have different instant of same object and also occupy different memory.

What is Mage in Magento?

The Mage::app() function is used to bootstrap your Magento application (setting up configuration, autoloading etc) and is useful when wanting to access Magento models in your own custom script for example.


1 Answers

Perfect differece with example for getsingleton and getmodel.

Mage::getSingleton()

Mage::getSingleton() will first check if the same class instance exists or not in the memory. If the instance exists then it will return the same object from the memory. So Mage::getSingleton() is faster than Mage::getModel().

Example

$product1 = Mage::getSingleton('catalog/product'); $product2 = Mage::getSingleton('catalog/product'); 

$product1 and $product2 both will share same memory of OS and return only one instance each time.

Mage::getModel()

Mage::getModel() will create a new instance of an object each time even such object exists in configuration.

Example

$product1 = Mage::getModel('catalog/product'); $product2 = Mage::getModel('catalog/product'); 

$product1 and $product2 both have different instant of same object and also occupy different memory

Mage::getResourceModel()

As far as I know, all collections in Magento are resource models. They are instantiated by

Mage::getResourceModel()  

or

Mage::getModel()->getCollection() 

It doesn't really matter which function you use; the latter one simply calls the first one. The Magento team simply chose to make collections part of the resource, probably because collections need to query the database a lot. Usually, you will not have to call Mage::getResourceModel() for anything else than collections.

good post by balajimca

like image 195
Sam Avatar answered Sep 24 '22 17:09

Sam