Magento getSingleton() vs getModel() issue

前端 未结 5 1108
时光取名叫无心
时光取名叫无心 2020-12-24 03:30

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         


        
5条回答
  •  抹茶落季
    2020-12-24 04:00

    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...

提交回复
热议问题