Asara
Asara

Reputation: 3374

Delete file when entity is deleted in symfony

I have an entity File() that can be deleted. Linked to the entity, there is an actual file in /upload with the name $file->getName(). When the File() entity is deleted, what is the best way to remove the file as well? Should I do it in the Controller, or can I put a method to File() that is triggered when the entity is destroyed?

Upvotes: 3

Views: 2125

Answers (1)

VTr
VTr

Reputation: 718

The best way to handle this case is using Doctrine lifecycle events (in your case, preRemove is a good choice).

You shouldn't handle it in your controller because your entity can be deleted any where (eg: in your service, cascade deletion...). Here is a list of Doctrine Events and Symfony documentation about How to Work with Lifecycle Callbacks or How to Register Event Listeners and Subscribers if you want to create your listener as a service with dependency injection.

Upvotes: 7

Related Questions