I want to loop over an array of product IDs in Magento. In the loop I am displaying some custom attributes of the products as:
foreach ($products as $product) {
$model = Mage::getSingleton('catalog/product')->load($product['id']);
echo '<br>' . $model->getCredits();
}
Problem is that if the value of getCredits()
for the first item is true
then all the subsequent items show true
even if they do not have the value true
.
But when I use Mage::getModel()
instead of Mage::getSingleton()
, the attribute values are displayed correct.
Can anyone please explain this difference?
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With