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 に答える