Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perform some cleanup when deleting a record in Symfony/Doctrine

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?

like image 611
HorusKol Avatar asked Jun 20 '10 12:06

HorusKol


3 Answers

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

like image 155
HorusKol Avatar answered Nov 15 '22 09:11

HorusKol


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.

like image 21
Colonel Sponsz Avatar answered Nov 15 '22 10:11

Colonel Sponsz


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.

like image 27
richsage Avatar answered Nov 15 '22 11:11

richsage