DDD / MVC:如何避免从View中访问Repository?

时间:2011-07-31 12:19:10

标签: model-view-controller orm domain-driven-design ddd-repositories repository

在阅读了其他几个问题后,看起来让实体类使用存储库是不可取的。所以给出了这些存储库:

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并不是我们所谓的“最佳实践”......

欢迎任何评论!

1 个答案:

答案 0 :(得分:3)

如果您需要与餐厅进行评论,您的餐馆储存库应该(可能选择)与餐厅一起检索。这些将作为一组评论以及每个餐馆的其他数据存储在类实例中。这将允许您构建一个更有效的查询,该查询将一次性获取所有数据并填充所需的对象。设计模式称为aggregate root

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) {
       ...
    }
}
?>