代码之家  ›  专栏  ›  技术社区  ›  Knowledge Craving

在Magento中使用产品的“getTypeInstance()”

  •  7
  • Knowledge Craving  · 技术社区  · 14 年前

    有谁能解释一下“getTypeInstance()”方法的需要吗?它可以被任何产品对象使用?

    还有什么好处;使用这种方法的缺点是什么?

    2 回复  |  直到 13 年前
        1
  •  17
  •   Judder    11 年前

    然后可以使用这些对象来确定特定于产品类型的产品信息。例如,如果对捆绑产品对象调用此方法,则会得到一个类为的对象

    Mage_Bundle_Model_Product_Type
    

    这个类上有许多方法,这些方法是专门为处理捆绑产品而设计的。例如,你有 getWeight 方法

    public function getWeight($product = null)
    {
        if ($this->getProduct($product)->getData('weight_type')) {
            return $this->getProduct($product)->getData('weight');
        } else {
            $weight = 0;
    
            if ($this->getProduct($product)->hasCustomOptions()) {
                $customOption = $this->getProduct($product)->getCustomOption('bundle_selection_ids');
                $selectionIds = unserialize($customOption->getValue());
                $selections = $this->getSelectionsByIds($selectionIds, $product);
                foreach ($selections->getItems() as $selection) {
                    $weight += $selection->getWeight();
                }
            }
            return $weight;
        }
    }
    

    然后,在 catalog/product 型号( Mage_Catalog_Model_Product 只需将调用包装到类型的 体重

    public function getWeight()
    {
        return $this->getTypeInstance(true)->getWeight($this);
    }
    

    是面向对象编程的一个典型例子。

    那么,今天结束了?如果您不知道为什么需要使用此方法,则不需要使用此方法。

        2
  •  4
  •   Joe Mastey    14 年前

    getTypeInstance 调用将返回不同的对象,具体取决于您选择的产品类型。例如,如果您选择了一个捆绑产品,那么type实例将包含关于其中捆绑产品的信息、关于如何计算动态权重的信息等。

    使用这个方法没有什么错,只要它有你需要的数据。

    谢谢, 乔