【问题标题】:Magento: when to use Mage::getResourceModel() aloneMagento:何时单独使用 Mage::getResourceModel()
【发布时间】:2012-08-14 20:41:00
【问题描述】:

除了使用集合时,是否有任何情况需要 Magento 开发人员使用 Mage::getResourceModel()

我现在在 Magento 开发了一段时间,还没有遇到需要单独使用 Mage::getResourceModel() 的情况。

【问题讨论】:

    标签: magento


    【解决方案1】:

    当您使用不属于标准 CRUD 模式的模型/资源模型对,并且您想直接调用资源模型的公共方法时。

    代码库中的一些示例(在我的脑海中)

    Mage/Admin/Model/Session.php
    100:                $this->setAcl(Mage::getResourceModel('admin/acl')->loadAcl());
    138:            $this->setAcl(Mage::getResourceModel('admin/acl')->loadAcl());
    
    Mage/Adminhtml/Block/Catalog/Product/Attribute/Set/Main.php
    179:        $configurable = Mage::getResourceModel('catalog/product_type_configurable_attribute')
    191:            $nodeChildren = Mage::getResourceModel('catalog/product_attribute_collection')
    233:        $collection = Mage::getResourceModel('catalog/product_attribute_collection')
    243:        $attributes = Mage::getResourceModel('catalog/product_attribute_collection')
    

    【讨论】:

      【解决方案2】:

      当您只想获取资源模型实例时,您应该使用getResourceModel(这也是对集合的某种优化,但集合是资源模型真的很愚蠢)。例如,为了获取资源模型,您可以使用:

      Mage::getModel('my_module/path_to_resource_model');
      

      此代码创建名称为My_Module_Model_Path_To_Resource_Model 的模型。但这不是一个好的解决方案,因为您可以在 config.xml 中指定资源模型类前缀(例如在 Mage_Cms 中):

      ............................................
              <models>
                  <cms>
                      <class>Mage_Cms_Model</class>
                      <resourceModel>cms_mysql4</resourceModel>
                  </cms>
                  <cms_mysql4>
      <!-- ----> --> <class>Mage_Cms_Model_Mysql</class>
      ............................................
      

      但是当您使用Mage::getResourceModel 时,系统会读取资源模型类前缀(您将来可以更改它)。所以,第一个代码sn-p可以改写为:

      Mage::getResourceModel('my_module/model');
      

      【讨论】:

      • 为什么将集合作为资源模型访问是“非常愚蠢的”?
      • @benmarks 因为它们不是资源。它们是业务模型的容器,因此集合也是资源模型是不合逻辑的(因此它们也是这个意义上的业务模型)。很少有方法可以揭示集合的实现(例如getSelect),这并不好。更好的商业模式是与馆藏共享资源模式。而在抽象集合类的load 内部方法应该类似于$this-&gt;getResource()-&gt;loadCollection($this);(或$this-&gt;getResource()-&gt;provideCollectionData(/* some arguments */);
      • @benmarks 您还可以在集合中找到很多混合的业务和 sql 逻辑。因此,这种情况使资源和业务之间的分离模型变得毫无用处。此外,您不能更改将加载集合的资源(您应该编写自己的集合)。
      猜你喜欢
      • 2023-03-22
      • 2014-02-04
      • 1970-01-01
      • 2011-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-26
      相关资源
      最近更新 更多