3

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?

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Wouldn't be postRemove better if eg. deletion fails because of foreign key constraint?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.