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?
Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.
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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0