Magento – Usage of getSingleton() and getModel()

classmodel

Is there a set of guidelines that I can go by to decide when I should use

   mage::getModel() and mage::getSingleton()

From what I can tell it seems as though getSingleton either gets an existing instance of a model/class or, only if one does not exist, creates a new instance. Whereas getModel() creates one regardless of what exists already. Is this correct?

Assuming I have the correct understanding of these, would it not make sense to always use mage::getSingleton()! It obviously doesn't or otherwise getModel() would not be used. So when should I use each one?

What is the main benefit to using these correctly? Should it improve performance, help avoid duplication or just generally apply best practice?

Best Answer

Yes, getSingleton returns the same instance, so you do not want to use it always, but only if you can live with having the same instance.

Example of when NOT to use a singleton:

$product = Mage::getModel('catalog/product');
$product->setSku("asdfasdf");
$product->setName("First Test Product");
$product->save();

$product = Mage::getModel('catalog/product');
$product->setSku("asdfasdf2");
$product->setName("Second Test Product");
$product->save();

This creates two products. But if you used Singleton, only one product would be created, the second one would overwrite the first one.