Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2: best approach to use business (repository) logic in entity or controller

I'm having a design issue in my project, related to where put some business logic.

I have three entities, Event, TicketOrder and Ticket. One Event has a lot of TicketOrders and one TicketOrder has a lot of Tickets.

In my template, I have to show how many tickets an Event has. I've thinking of the best approach to achieve this and didn't get a good solution. I've tried this:

1) Create a private member 'ticketsCount' in Event entity, with setTicketsCount and getTicketsCount method. Create a 'loadTicketsCount' method with a LifeCycleCallback 'PostLoad', to access the TicketRepository method 'findByEvent'. This was impossible because I can't access repository in an entity class.

2) In the action that will be used to display the Event, I can access Ticket Repository and set event 'ticketsCount' property manually. I don't know if it is a good approach because if my action is listing a lot of events I'll have to loop trough all events and make a repository call to each of then.

I really don't know the best approach to achieve this and will really appreciate if someone can help me.

Thanks! ;)

like image 766
Hugo Nogueira Avatar asked Nov 03 '22 03:11

Hugo Nogueira


1 Answers

When you use findAll, findBy or findBy* methods of doctrine entity repository, a simple php array is returned containing the entity objects.

The array class implements countable interface. So using twigs length filter

{{ ticketOrder.tickets|length }}

you perform a simple php count() on the array.

Actually it makes now sense to perform a count query, because you already have the result in memory. So it seems more efficient to count the result and retrieve it from memory, because when you access associations they are completely loaded into memory.


However associations between entities can get pretty large. So imagine you have associations with hundred thousands of entities. You won't those entites to be loaded all together and kept in memory all the time. So in Doctrine 2.1 you can annotate an association as Extra Lazy. If you do so in your case a count query is performed when you call the above twig filter. But the result is not kept in memory.

http://docs.doctrine-project.org/en/2.0.x/tutorials/extra-lazy-associations.html


According to your latest comment:

I can imagine one way to do this. In a template you can call a controller's action with the render statement like

{% render YourMainBundle:getTickets with { 'event_id' : event.id } %}

and in this action you can call a query that looks for all tickets associated to the certain event. This action has to return html, e.g. an template filled with data.

like image 162
UpCat Avatar answered Nov 09 '22 17:11

UpCat