load商品对象在magento中是很常见的,但是load一次商品对象消耗性能是很大的,因为load的时候会触发很多事件,所以经常load对服务器压力是很大的,有的时候可能只需要很少的数据,但是我们load就会得不偿失,所以这里使用一个轻量级的load;
$product = Mage::getModel('catalog/product')->setLite(true)->load($product->getId());
原生magento在load时候代码如下:
public function load($id, $field=null)
{
$this->_beforeLoad($id, $field);
$this->_getResource()->load($this, $id, $field);
$this->_afterLoad();
$this->setOrigData();
$this->_hasDataChanges = false;
return $this;
}
load时候会触发_beforeLoad和_afterLoad,我们看下这两个里面是什么样的:
protected function _beforeLoad($id, $field = null)
{
$params = array('object' => $this, 'field' => $field, 'value'=> $id);
Mage::dispatchEvent('model_load_before', $params);
$params = array_merge($params, $this->_getEventData());
Mage::dispatchEvent($this->_eventPrefix.'_load_before', $params);
return $this;
}
protected function _afterLoad()
{
Mage::dispatchEvent('model_load_after', array('object'=>$this));
Mage::dispatchEvent($this->_eventPrefix.'_load_after', $this->_getEventData());
return $this;
}
通过代码可以看出在load时候会触发很多事件,所以load一次是很大的,经常load对服务器压力是很大的;
这里我们对特定的load进行重写处理:
config.xml
<models>
<catalog>
<rewrite>
<product>Fun_Catalog_Model_Product</product>
</rewrite>
</catalog>
</models>
/**
* 处理特定load
*/
public function load($id, $field=null)
{
if($this->getLite()){
$this->_getResource()->load($this, $id);
return $this;
}
return parent::load($id);
}
通过代码可以看出这里为什么我们在load前加上setLite()并且值为true,代码中我们可以看到这里是直接使用资源层进行load,这样就会减少很多model层load触发的很多事件,会减轻很大的服务器压力,尤其是在购物车中,在大于10件的时候效果是十分明显的。
但是这里要注意根据实际需求来决定是否使用轻量级load,毕竟使用这种轻量级方法在商品对象中会少一些东西