3

在阅读了其他几个问题之后,似乎不建议让实体类使用存储库。因此,鉴于这些存储库:

class RestaurantRepository {
    public function findAll() { ... }
}

class ReviewRepository {
    public function findByRestaurant(Restaurant $restaurant) { ... }
}

我不应该在课堂上这样做:

class Restaurant {
    public function getReviews() {
        // ...
        return $restaurantRepository->findByRestaurant($this);
    }
}

但是假设我有这个控制器,它为视图提供了一个餐厅列表:

class IndexController {
    public function indexAction() {
        $restaurants = $restaurantRepository->findAll();
        $this->view->restaurants = $restaurants;
    }
}

在视图脚本中获取每家餐厅的评论的“良好做法”是什么?因此我不能这样做:

foreach ($this->restaurants as $restaurant) {
    $reviews = $restaurant->getReviews();
}

而且我想在视图中注入 ReviewRepository 也不是我们所说的“最佳实践”......

欢迎任何评论!

4

1 回答 1

3

如果您需要与餐厅一起获得评论,您的餐厅存储库应该(也许,可选地)与餐厅一起检索这些评论。这些将作为评论的集合与每个餐厅的其他数据一起存储在类实例中。这将允许您构建一个更有效的查询,该查询将一次性获取所有数据并填充所需的对象。该设计模式称为聚合根

class RestaurantRepository {
    public function findAll($withReviews = 0) { ... }
}

class IndexController {
    public function indexAction() {
        $restaurants = $restaurantRepository->findAll(1);
        $this->view->restaurants = $restaurants;
    }
}

<?php
foreach ($this->restaurants as $restaurant) {
    foreach ($restaurant->reviews as $review) {
       ...
    }
}
?>
于 2011-07-31T12:42:13.600 回答