Note that there are some explanatory texts on larger screens.

plurals
  1. POSymfony2 Best practices - sorting of entities
    text
    copied!<p>I am creating an application in Symfony2. This is the first time I develop using a framework and one of my first projects. It is a student project.</p> <p>In this project, I want my collections of entities to be sorted somewhere before reaching the view. This can be done in this way:</p> <p>In getters on the entities on the many-to-one relations, with comparator methods on the many-side that is used by the usort() method in the getter on the one-side. Below I have a method that also fills in gaps in a collection of "Day" entities (in a form of diary), but the point is that it sorts the days with usort.</p> <p>In User entity class:</p> <pre><code>public function getDaysWithNulls() { $days = $this-&gt;getDays()-&gt;toArray(); //get the first day and find out how many days have passed usort($days, array("\Pan100\MoodLogBundle\Entity\Day", "daySorter")); $firstEntry = $days[0]; $interval = $firstEntry-&gt;getDate()-&gt;diff(new \DateTime()); $numberOfDaysBack = $interval-&gt;d; //create an array consisting of the number of days back $daysToShow = array(); for ($i=0; $i &lt; $numberOfDaysBack ; $i++) { $date = new \DateTime(); $date-&gt;sub(new \DateInterval('P' . $i . 'D')); $daysToShow[] = $date; } $daysToReturn = array(); foreach ($daysToShow as $day) { //figure out if this day has an entity, if not set an empty Day object $dayEntityToProcess = new \Pan100\MoodLogBundle\Entity\Day(); $dayEntityToProcess-&gt;setDate($day); foreach ($days as $dayEntity) { //check if there is a day entity if($day-&gt;format('Y-m-d') == $dayEntity-&gt;getDate()-&gt;format('Y-m-d')) { $dayEntityToProcess = $dayEntity; } } $daysToReturn[] = $dayEntityToProcess; } //return a collection return new \Doctrine\Common\Collections\ArrayCollection($daysToReturn); } </code></pre> <p>usort uses this in the Day entity class:</p> <pre><code>static function daySorter($dayEntity1, $dayEntity2) { $interval = $dayEntity1-&gt;getDate()-&gt;diff($dayEntity2-&gt;getDate()); if($interval-&gt;invert == 1) { return +1; } else if ($interval-&gt;invert == 0) { return 0; } else return -1; } </code></pre> <p><strong>My question is: is this the best practice for sorting and returning sorted collections, or should sorting happen somewhere else?</strong></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload