Magento getSingleton()vs getModel()问题

Arv*_*waj 14 php singleton magento

我想在Magento中循环遍历一系列产品ID.在循环中,我将产品的一些自定义属性显示为:

foreach ($products as $product) {
   $model = Mage::getSingleton('catalog/product')->load($product['id']);
   echo '<br>' . $model->getCredits();
}
Run Code Online (Sandbox Code Playgroud)

问题是,如果getCredits()第一项的值是,true那么true即使它们没有值,所有后续项也会显示true.

但是当我使用Mage::getModel()而不是时Mage::getSingleton(),属性值显示正确.

有人可以解释这个区别吗?

Ken*_*nny 30

Mage :: getModel()将始终返回给定模型的新Object:

/**
 * 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);
}
Run Code Online (Sandbox Code Playgroud)

Mage :: getSingleton()将检查给定模型的Object是否已经存在,如果存在则返回.如果它不存在,它将创建给定模型的新对象并将其存在于注册表中.下一次调用不会返回新对象,而是返回现有对象:

/**
 * 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);
}
Run Code Online (Sandbox Code Playgroud)

在您的情况下,您总是需要一个全新的Product对象/模型,因为每个产品都是独一无二的......


Mar*_*ius 10

getModel将每次返回所请求模型的新实例.
getSingleton将始终返回相同的实例.这是Magento的Singleton设计模式的实现.
您还必须牢记其他方面.该load方法不会删除您在产品实例上设置的所有数据.例如,如果你这样做:

$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
Run Code Online (Sandbox Code Playgroud)

This is the case for you. By using 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.


Suk*_*ini 5

首先我想解释一下 difference between Mage::getSingleton() and Mage::getModel() functions.

当您调用该函数时,Mage::getSingleton('catalog/product')magento 将在内存中搜索是否有任何可用的对象。如果不是,它将为Mage_catalog_Model_product类创建一个新对象。在 foreach 循环的第一次迭代中会发生这种情况。但是从第二次迭代开始,当 magento 在内存中搜索 Mage_catalog_Model_product 类对象时,它将找到在第一次迭代中调用的对象。所以 magento 不会创建任何新对象,而是会调用内存中已经存在的相同对象。

但,

如果您使用Mage::getModel('catalog/product)此函数Mage_catalog_Model_product,则无论何时调用它,都始终在内存中创建新的类对象。因此,在循环中,此函数将在每次迭代中创建一个对象。