Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony, where to put custom methods on entities?

Tags:

php

symfony

I'm learning Symfony and I'm trying to figure out where to put custom actions over an Entity...

For example, if I have an entity Order, where to put $order->complete()? Or $order->sendToProduction(), $order->queueForDelivery()?

Those are just examples, I have complex entities and I must perform on them many actions.

In the Controller?

  • No, because the same action may be called from different controllers

In the Entity?

  • That would be the more appropriate way in a MVC model, but here I can't find an easy way to perform custom mysql query (doctrine/em is not available) from inside the Entity class, which I find strange since db operations should be perfomed at the Entity level, I believe...

In the EntityController?

  • It doesn't seem appropriate, and it's not easy to call repository methods from a listener, for example, and call them directly on the object...

What else? Do I have to create services? Utility classes?

like image 363
the_nuts Avatar asked Jun 10 '16 07:06

the_nuts


1 Answers

If the work can be done inside a signle entity (and it's relations of course) then it should be placed there. I mean, if the operation is about changing entity's internal state.

Otherwise, if this job need to use other parts of application like database, or is performed on multiple not related entites, then I would suggest using services.

That's what where are for. Service is basically a class that can do anything. Using Service container, you can pass any dependencies to it so it's very flexible and easy to use.

For example $order->queueForDelivery(). That may mean a few different things:

  • changing internal state like change status to queued_for_delivery - then it should be in Order entity class
  • $order should be put in the Queue that is other entity class, then it should be in Queue class like $queue->addOrder($order)
  • this queue is an external service like RabbitMQ or anything else. Then you should use a service class.
like image 127
Jakub Matczak Avatar answered Sep 25 '22 23:09

Jakub Matczak