我想在 Magento 中遍历一系列产品 ID.在循环中,我将产品的一些自定义属性显示为:
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();
}
问题是,如果第一项的 getCredits() 值为 true,那么所有后续项都显示 true,即使它们没有值 true.
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.
但是当我使用 Mage::getModel() 而不是 Mage::getSingleton() 时,属性值显示正确.
But when I use Mage::getModel() instead of Mage::getSingleton(), the attribute values are displayed correct.
谁能解释一下这个区别?
Can anyone please explain this difference?
Mage::getModel() 将始终为给定模型返回一个新对象:
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() 将检查给定模型的对象是否已经存在,如果存在则返回.如果它不存在,它将创建一个给定模型的新对象,并将其放入已存在的注册表中.下一次调用不会返回新对象,而是返回现有对象:
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);
}
在您的情况下,您总是想要一个全新的 Product 对象/模型,因为每个产品都是独一无二的...
In your case you always want a completely new Product object/model since every product is unique...
这篇关于Magento getSingleton() 与 getModel() 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
在 SELECT(MYSQL/PHP) 中加入 2 个表Joining 2 tables in SELECT(MYSQL/PHP)(在 SELECT(MYSQL/PHP) 中加入 2 个表)
如何使<option selected=“selected">由How to make lt;option selected=quot;selectedquot;gt; set by MySQL and PHP?(如何使lt;option selected=“selectedgt;由 MySQL 和 PHP 设置?)
使用 PHP 中的数组自动填充选择框Auto populate a select box using an array in PHP(使用 PHP 中的数组自动填充选择框)
PHP SQL SELECT where like search item with multiple wordsPHP SQL SELECT where like search item with multiple words(PHP SQL SELECT where like search item with multiple words)
json_encode 从 MSSQL-SELECT 产生 JSON_ERROR_UTF8json_encode produce JSON_ERROR_UTF8 from MSSQL-SELECT(json_encode 从 MSSQL-SELECT 产生 JSON_ERROR_UTF8)
MySQL ORDER BY rand(),名称 ASCMySQL ORDER BY rand(), name ASC(MySQL ORDER BY rand(),名称 ASC)