【问题标题】:DDD/MVC: how to avoid hitting the Repository from the View?DDD/MVC:如何避免从视图中访问存储库?
【发布时间】:2011-07-31 12:19:09
【问题描述】:

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

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

欢迎评论!

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 感谢您的回答。实际上,Restaurant 和 Review 都是聚合根(Review 有一个 Restaurant 和一个 User,并且有自己的 Repository)。评论可以在餐厅之外创建,因此据我了解,它不是餐厅聚合的一部分。因此,Restaurant 的 Review 集合 是否仍应由 Restaurant 存储库填充?
    • 我终于意识到,我不需要每家餐厅的所有评论,而只需要它们的摘要。因此,我将评论统计信息(评论数量、平均评分)放在了 Restaurant 实体中,并且不再需要访问 ReviewRepository。如果我需要这样做,我只需引入一个包含餐厅及其评论的值对象,并将其传递给视图。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-06
    • 1970-01-01
    • 2021-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多