在Magento后台删除产品时,默认不会删除产品的图片,如果长期不清理这些废弃的图片,会导致Media目录下的文件越来越多,浪费服务器空间,为了实现删除产品的同时删除图片,从网络上得知常见的方法是修改Mage_Catalog_Model_Product的delete()方法:
把
public function delete()
{
parent::delete();
Mage::dispatchEvent($this->_eventPrefix.’_delete_after_done’, array($this->_eventObject=>$this));
return $this;
}
修改为
public function delete()
{
parent::delete();
Mage::dispatchEvent($this->_eventPrefix.’_delete_after_done’, array($this->_eventObject=>$this));
foreach ($this->getMediaGallery(‘images’) as $image) {
$image_path = $this->getMediaConfig()->getMediaPath($image['file']);
if (file_exists($image_path)) {
@unlink($image_path);
}
}
return $this;
}
这个方法是通过重写Model的方法实现的,下面我们将采用事件触发的方法来实现,我们观察在delete()函数中触发了catalog_product_delete_after_done事件,因此我们可以写一个插件,当观察到这个事件时删除产品的图片。
1 新建模块
在/app/code/local/MagentoBoy/DeleteProductImages目录下新建一个模块MagentoBoy_DeleteProductImages,并添加模块文件:
/app/etc/modules/MagentoBoy_DeleteProductImages.xml
<?xml version=”1.0″?>
<config>
<modules>
<MagentoBoy_DeleteProductImages>
<active>true</active>
<codePool>local</codePool>
</MagentoBoy_DeleteProductImages>
</modules>
</config>
并添加配置文件:
/app/code/local/MagentoBoy/DeleteProductImages/etc/config.xml
<?xml version=”1.0″?>
<config>
<modules>
<MagentoBoy_DeleteProductImages>
<version>0.1.0</version>
</MagentoBoy_DeleteProductImages>
</modules>
</config>
2 添加Observer
/app/code/local/MagentoBoy/DeleteProductImages/Model/Observer.php
<?php
class MagentoBoy_DeleteProductImages_Model_Observer
{
public function processProductAfterDeleteEvent(Varien_Event_Observer $observer)
{
$eventProduct = $observer->getEvent()->getProduct();
if ($eventProduct && $eventProduct->getId()) {
foreach ($eventProduct->getMediaGallery(‘images’) as $image) {
$image_path = $eventProduct->getMediaConfig()->getMediaPath($image['file']);
if (file_exists($image_path)) {
@unlink($image_path);
}
}
}
return $this;
}
}
并在config.xml中添加models和events
<config>
<global>
<models>
<deleteproductimages>
<class>MagentoBoy_DeleteProductImages_Model</class>
</deleteproductimages>
</models>
<events>
<catalog_product_delete_after_done>
<observers>
<deleteproductimages>
<class>deleteproductimages/observer</class>
<method>processProductAfterDeleteEvent</method>
</deleteproductimages>
</observers>
</catalog_product_delete_after_done>
</events>
</global>
</config>
这样就实现了在Magento中删除产品同时删除图片的功能,使用事件触发的方式更为灵活,方便在多个模块中扩展功能。
(责任编辑:最模板) |