Symfony, where to put custom methods on entities?

I am learning Symfony and I am trying to figure out where to put custom actions on Entity ...

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

These are just examples, I have complex objects, and I have to perform many actions on them.

In the controller?

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

In Entity?

  • This would be a more suitable way in the MVC model, but here I cannot find an easy way to execute the mysql custom query (doctrine / em is not available) from the Entity class, which I find strange, since db I believe that operations should be performed at the Entity level. ..

In an EntityController?

  • This does not seem appropriate, and, for example, it is not easy to call repository methods from a listener, for example, and call them directly on the object ...

What else? Should I create services? Utilities?

+5
source share
1 answer

If the work can be done inside the signle object (and, of course, this is a relationship), then it should be placed there. I mean, if the operation is associated with a change in the state of an internal object .

Otherwise, if this task needs to use other parts of the application, such as a database, or is performed on several issues unrelated to it, I would suggest using services .

What for what. A service is basically a class that can do something. Using the Service container, you can transfer any dependencies to it so that it is very flexible and easy to use.

For example $order->queueForDelivery() . This can mean several different things:

  • change the internal state, for example change status , to queued_for_delivery - then it should be in the Order entity class
  • $order should be placed in Queue , which is another essential class, then it should be in the Queue class, as $queue->addOrder($order)
  • this queue is an external service such as RabbitMQ or something else. Then you should use the service class.
+7
source

All Articles