在Magento中使用Product的"getTypeInstance()"

Kno*_*ing 8 php oop magento

任何人都可以对"getTypeInstance()"方法的需要有所了解,可以被任何产品对象使用吗?

使用这种方法的优点和缺点是什么?

Ala*_*orm 17

getTypeInstance允许您检索描述产品类型的对象,其中type是内部magento类型.因此,您可以使用此方法来确定产品是简单产品,捆绑产品,可配置产品等.

然后,您可以使用这些对象来确定有关特定于其类型的产品的信息.例如,如果在捆绑的产品对象上调用此方法,则将获得其类为的对象

Mage_Bundle_Model_Product_Type
Run Code Online (Sandbox Code Playgroud)

该类有许多方法,专门用于处理捆绑产品.例如,您有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;
    }
}
Run Code Online (Sandbox Code Playgroud)

该方法具有用于确定捆绑产品的重量的特定规则.

然后,在catalog/productModel(Mage_Catalog_Model_Product)中,您可以看到getWeight只包含对类型的调用getWeight

public function getWeight()
{
    return $this->getTypeInstance(true)->getWeight($this);
}
Run Code Online (Sandbox Code Playgroud)

这是面向对象编程的一个主要例子.

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