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

时光毁灭记忆、已成空白 提交于 2019-12-05 01:26:20

问题


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! ;)


回答1:


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.



来源:https://stackoverflow.com/questions/15101087/symfony2-best-approach-to-use-business-repository-logic-in-entity-or-controll

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!