【问题标题】:Magento-when to use Mage::getResourceModel and Mage::getModelMagento-何时使用 Mage::getResourceModel 和 Mage::getModel
【发布时间】:2014-02-04 21:34:30
【问题描述】:

我刚开始使用 Magento,特别是关于模型和 ORM 的工作原理。

这三种方法我都用过

Mage::getResourceModel()
Mage::getModel()
Mage::getSingleton()

谁能告诉我它们之间的区别是什么?

我发现getSingleton() 共享内存,而getModel() 为正在加载的同一个表的新对象使用新内存。

上述所有方法我都用过,但无法区分它们以及何时适合使用哪一种。

【问题讨论】:

    标签: magento


    【解决方案1】:

    getsingleton 和 getmodel 示例的完美区别。

    法师::getSingleton()

    Mage::getSingleton() 将首先检查内存中是否存在相同的类实例。如果实例存在,那么它将从内存中返回相同的对象。所以 Mage::getSingleton() 比 Mage::getModel() 快。

    例子

    $product1 = Mage::getSingleton('catalog/product');
    $product2 = Mage::getSingleton('catalog/product');
    

    $product1 和 $product2 都将共享相同的操作系统内存,并且每次只返回一个实例。

    Mage::getModel()

    即使配置中存在这样的对象,Mage::getModel() 也会创建一个对象的新实例。

    例子

    $product1 = Mage::getModel('catalog/product');
    $product2 = Mage::getModel('catalog/product');
    

    $product1 和 $product2 对同一个对象有不同的瞬间,也占用不同的内存

    Mage::getResourceModel()

    据我所知,Magento 中的所有集合都是资源模型。它们由

    实例化
    Mage::getResourceModel() 
    

    Mage::getModel()->getCollection()
    

    你使用哪个函数并不重要;后一个简单地调用第一个。 Magento 团队只是选择将集合作为资源的一部分,可能是因为集合需要大量查询数据库。通常,您无需致电 Mage::getResourceModel() 获取收藏以外的任何内容。

    balajimca 的好帖子

    【讨论】:

    • 上帝保佑你这个解释。
    • 如何使用类别ID在观察者中调用选定的产品类别? @山姆
    【解决方案2】:

    此外,如果您知道需要哪些属性,那么使用 Mage::getResourceModel 和过滤器在速度和内存方面的效率比通过 Mage::getModel('catalog/product') 加载要高约 5 倍。

    例如 从数据库中检索产品的 getResourceModel 方法

    $collection = Mage::getResourceModel('catalog/product_collection')
        ->addFieldToFilter('entity_id', array($productId))
        ->addAttributeToSelect(array('name'))
        ->setPageSize(1);
    $product = $collection->getFirstItem();
    

    加载模型(这将加载所有 eav 属性)

    Mage::getModel('catalog/product')->load($productId);
    

    [更多信息在这里][1] http://alanstorm.com/magento_advanced_orm_entity_attribute_value_part_1

    【讨论】:

    • 这有帮助,但我不得不在扩展Mage_Core_Model_Resource_Db_Collection_Abstract的非基于产品的具体类上使用->addFieldToSelect('name_of_field')
    • @LeoFisher 是的,您需要对非 EAV 集合使用 addFieldToSelect([])
    猜你喜欢
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2012-11-03
    • 2013-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多