Problem
I am trying to optimize the architecture of my web-application developed in PHP using the Symfony framework.
I have an object “pool” that contains “swimmers”. I need to display the number of swimmers in my pool, but only those with a pink bath-suit.
In order to do this, I see many possible approaches :
Approaches
-
Create a custom getter method in my Pool class, and filters the swimmers by bath suits color :
public function getSwimmersInPinkSuit() { for each($this->getSwimmers() as $swimmer) { if($swimmer->getBathSuitColor() == "pink") { $pinkSwimmers[] += $swimmer; } return $pinkSwimmers; }
{{ pool.getSwimmersInPinkSuit | length }}
-
Create a custom SQL query in my controller, define the number there before sending it to my template.
-
Add a “$pinkSwimmers” property to my Pool class, and increment/decrement it with an eventListener every time I persist in database the event “a pinkSwimmer joins/leaves the pool”. I then can access the value where i want :
{{ pool.pinkSuits }}
-
Use a denser twig request to filter out the pink swimmers directly in my template
{{ pool.swimmers.suitColor(“pink”) | lenght }} // If that’s even possible o0
Question
In the four propositions above, I see pros and cons to each of them, so :
- What is the best practice in this situation ? Am I overseeing a better logic in addition to the ones mentioned above ? I try to find an implementation that would be lightweight in term of performance (memory, bandwidth), but also easy to reconfigure (change from pink to green suits, or from suit color to swimming style).
4
From the comments, it appears as though you are searching 250 swimmers with 25 properties each.
Even if this is done by application code, it should still take an unnoticeable amount of time, unless you are making N queries per swimmer, or any sort of complex lookup per swimmer. If this is the case, look up the N+1 select problem and use the minimum number queries/lookups to build your swimmers.
SO answer on N+1 select
PHP article on N+1 select