Friday, November 21, 2014

Difference between Mage::getSingleton() and Mage::getModel() in Magento

Hello all of you today I will explain you what is Difference between Mage::getSingleton() and Mage::getModel() in Magento.


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

$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() will create a new instance of an object each time even such object exists in configuration.


$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 .

Hope you like this.


Mage::getModel() will always return a new Object for the given model:
 * Retrieve model object
 * @link    Mage_Core_Model_Config::getModelInstance
 * @param   string $modelClass
 * @param   array|object $arguments
 * @return  Mage_Core_Model_Abstract|false
public static function getModel($modelClass = '', $arguments = array())
    return self::getConfig()->getModelInstance($modelClass, $arguments);

Mage::getSingleton() will check whether the Object of the given model already exists and return that if it does. If it doesn't exist, it will create a new object of the given model and put in registry that it already exists. Next call will not return a new object but the existing one:
 * Retrieve model object singleton
 * @param   string $modelClass
 * @param   array $arguments
 * @return  Mage_Core_Model_Abstract
public static function getSingleton($modelClass='', array $arguments=array())
    $registryKey = '_singleton/'.$modelClass;
    if (!self::registry($registryKey)) {
        self::register($registryKey, self::getModel($modelClass, $arguments));
    return self::registry($registryKey);
In your case you always want a completely new Product object/model since every product is unique.

No comments: