【问题标题】:Symfony2 Best practices - sorting of entitiesSymfony2 最佳实践 - 实体排序
【发布时间】:2013-04-02 03:37:48
【问题描述】:

我正在 Symfony2 中创建一个应用程序。这是我第一次使用框架进行开发,也是我的第一个项目之一。这是一个学生项目。

在这个项目中,我希望在到达视图之前对我的实体集合进行排序。这可以通过这种方式完成:

在多对一关系实体的 getter 中,在多端具有比较器方法,由一侧 getter 中的 usort() 方法使用。下面我有一个方法,它也可以填补“Day”实体集合中的空白(以日记的形式),但重点是它使用 usort 对日期进行排序。

在用户实体类中:

public function getDaysWithNulls()
    {
    $days = $this->getDays()->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->getDate()->diff(new \DateTime());
    $numberOfDaysBack = $interval->d;
    //create an array consisting of the number of days back
    $daysToShow = array();
    for ($i=0; $i < $numberOfDaysBack ; $i++) { 
        $date = new \DateTime();
        $date->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->setDate($day);
        foreach ($days as $dayEntity) {
            //check if there is a day entity
            if($day->format('Y-m-d') == $dayEntity->getDate()->format('Y-m-d')) {
                $dayEntityToProcess = $dayEntity;
            } 
        }
        $daysToReturn[] = $dayEntityToProcess;
    }
    //return a collection
    return new \Doctrine\Common\Collections\ArrayCollection($daysToReturn);
}

usort 在 Day 实体类中使用这个:

static function daySorter($dayEntity1, $dayEntity2) {
    $interval = $dayEntity1->getDate()->diff($dayEntity2->getDate());
    if($interval->invert == 1) {
        return +1;
    }
    else if ($interval->invert == 0) {
        return 0;
    }
    else return -1;
}

我的问题是:这是排序和返回排序集合的最佳做法,还是应该在其他地方进行排序?

【问题讨论】:

  • 一点评论:我在某处读到不应使用实体类中的 EntityManager 进行查询,因为它会绑定图层。否则我可以查询 EntityManager 的按天排序的天数。

标签: model-view-controller sorting symfony architecture doctrine


【解决方案1】:

我确实认为这是一种乏味的做法。所以我在网上搜索了一下,又看了一些,发现我可以创建自定义存储库。

我会这样做:

http://symfony.com/doc/2.1/book/doctrine.html#custom-repository-classes

编辑:发现在注释中排序更好:

/**
 * @ORM\OneToMany(targetEntity="Day", mappedBy="user_id")
 * @ORM\OrderBy({"date" = "DESC"})     
 **/    
protected $days;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-02
    • 2014-02-04
    • 1970-01-01
    • 2014-06-21
    • 1970-01-01
    • 1970-01-01
    • 2013-05-07
    • 1970-01-01
    相关资源
    最近更新 更多