getModel
will return a new instance of the requested model every time.getSingleton
will always return the same instance. It's the implementation of the Singleton design pattern for Magento.There is also an other aspect that you have to keep in mind. The
load
method does not remove all the data you have set on the product instance. For example if you do this:$model = Mage::getModel('catalog/product')->setData('some_field_that_does_not_exist', 1);
$model->load(3);
echo $model->getData('some_field_that_does_not_exist'); //this prints 1
This is the case for you. By using
Conclusion: Do not use
getSingleton
the second time, you get the same product instance as the first time. And when calling load
the value for credits
is not overwritten because there is no such value on the newly loaded product.Conclusion: Do not use
getSingleton
. Use getModel
. Or if you want to use getSingleton
use $model->setData(array())
before calling load
. This will reset all the attributes.
Answer 2:
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...
0 comments:
Post a Comment