Models in Magento

Working with data in Magento is based on three principles: models, resource models and collections. There are different ways and methods to do same thing and we would like to shed some light on the differences.

Magento utilizes Singleton Pattern in form of storing data in global registry. Here comes the difference between Mage::getModel() and Mage::getSingleton() methods, the latter checks if the requested class is already instantiated and if that is true – returns object from registry. Otherwise, class is instantiated and stored into registry.

 

To retrieve resource models you have similar set of methods come handy, they are Mage::getResourceModel() and Mage::getResourceSingleton(). And if you have a model object, its accompanying resource module can be retrieved using Mage::getModel()->getResource() method.

 

Let’s get to the third whale – the collections. For the sake of simplicity collections are set of models, if a model presents table row as object, a collection presents a set of rows. Getting a collection is as easy as Mage::getModel()->getCollection(). There is, however, a bit shorter notation Mage::getResourceModel('module/model_collection') which is basically the same, if you take a look at Mage_Core_Model_Abstract::getResourceCollection() method, but allows you to skip instantiating the model class.

 

I hope this brief overview of models and related stuff was useful for you and if there are any questions or unclear points feel free to let us know in the comments.