3

몇 가지 다른 질문을 읽은 후에 엔티티 클래스에서 리포지토리를 사용하는 것은 좋지 않은 것처럼 보입니다. 그래서 주어진이 저장소 :DDD/MVC :보기에서 저장소를 치는 것을 피하려면?

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을 주입하는 것은 우리가 "가장 좋은 방법"을뿐만 아니라 호출 할 수있는 일이 아니라고 생각 : 그래서 저는이 작업을 수행 할 수 있습니다!

답변

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

답장을 보내 주셔서 감사합니다. 실제로 Restaurant과 Review는 모두 집계입니다 (리뷰에는 Restaurant 및 User가 있으며 자체 리포지토리가 있습니다). 리뷰는 식당 외부에서 만들 수 있으므로 내 이해에있어 레스토랑 집계의 일부가 아닙니다. 따라서 Restaurant의 * Review 콜렉션 *은 여전히 ​​Restaurant 저장소에 의해 채워 져야합니까? – Benjamin

+0

나는 마침내 내가 각 레스토랑에 대한 모든 리뷰를 필요로하지 않는다는 것을 알았다. 따라서 나는 리뷰 엔터티에 리뷰 통계 (리뷰 수, 평균 평점)를 넣었으며 더 이상 ReviewRepository에 액세스 할 필요가 없습니다. 그리고 이것을해야한다면, 리뷰와 함께 식당을 포함 할 가치 객체를 도입하고 이것을 뷰에 전달할 것입니다. – Benjamin

관련 문제