Perform some cleanup when deleting a record in Symfony/Doctrine

拜拜、爱过 提交于 2019-12-06 01:48:28

问题


Using Symfony 1.4.5 with Doctrine

I have a model which includes an uploaded image as one of the columns - creating and updating the record is fine (using the doSave() method to deal with the upload and any changes to the file).

The problem I'm having is if the record is deleted - I want it to remove the associated file as well. But I can't find anyway to do this after several hours of hunting through documentation and Google.

Is there a way to specify some kind of post-delete code?


回答1:


Final solution:

in /lib/model/doctrine/Image.class.php

class Image extends BaseImage
{
  public function postDelete()
  {
    $filename = $this->getFilename();

    $filepath = sfConfig::get('sf_upload_dir') . '/' . $filename;
    @unlink($filepath);
  }
}

Thanks to Colonel Sponz for pointing me in the right direction




回答2:


It's a while since I last used Doctrine but I seem to remember there is a post delete hook function that you can use for this kind of thing. If you look into the source for the Doctrine base class you should be able to find the exact method name and usage.

EDIT: The method is postDelete() and is found in the Doctrine_Record class

Here's the section from the Symfony documentation that covers advanced Doctrine usage.




回答3:


Hijacking Colonel Sponsz's answer, the postDelete() method is definitely the way to go. +1 to him :-) But, you'll need to enable Doctrine callbacks in your config/ProjectConfiguration.class.php. Add this method:

public function configureDoctrine(Doctrine_Manager $manager)
{
  $manager->setAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS, true);
}

Clear your Symfony cache, and Doctrine will fire the callback methods such as postDelete() at the appropriate times.



来源:https://stackoverflow.com/questions/3079146/perform-some-cleanup-when-deleting-a-record-in-symfony-doctrine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!