2012-06-26 2 views
3

symfony 2 프레임 워크를 조사하고 있습니다. 내 샘플 앱에는 Blog 엔터티와 BlogEntry 엔터티가 있습니다. 그들은 일대 다 관계로 연결되어 있습니다. 이 블로그 항목 클래스입니다 :엔티티 객체 symfony 2에서 doctrine 호출

class BlogEntry 
{ 
    .... 
    private $blog; 
    .... 
    public function getBlog() 
    { 
     return $this->blog; 
    } 

    public function setBlog(Blog $blog) 
    { 
     $this->blog = $blog; 
    } 
} 

나는 이런 식 참조, 블로그 항목 클래스에 메소드 setBlogByBlogId를 추가 할 :

public function setBlogByBlogId($blogId) 
    { 
     if ($blogId && $blog = $this->getDoctrine()->getEntityManager()->getRepository('AppBlogBundle:Blog')->find($blogId)) 
     { 
      $this->setBlog($blog); 
     } 
     else 
     { 
      throw \Exception(); 
     } 
    } 

이 모델 클래스의 교리를 얻을 수있는 방법입니다? 이것은 Symfony 2 MVC 아키텍처의 관점에서 맞습니까? 아니면 내 컨트롤러에서해야합니까?

+0

난 당신의 코드가 관계를 정의하는 교리에 너무 복잡하다라고 말하고 싶지만. 여기에 어떤 방향도 제시하지 않고 단지 너무 복잡하다고 말합니다. 관계를 만드는 방법을 다시 읽는 것이 좋습니다. 아마도 기술적 인면에서는 정확하지만 너무 지나치게 길 것입니다. – hakre

+0

교리에 무엇이 복잡합니까? 일대 다 관계? 나는 너를 아주 잘 이해하지 못한다고 생각한다. – Ris90

답변

5

BlogIntry 엔티티에 블로그 개체를 설정하기 전에 BlogId를 사용하여 저장소에 블로그 개체를 쿼리해야합니다.

블로그 개체가 있으면 BlogEntry 엔터티에서 setBlog ($ blog)를 호출하기 만하면됩니다.

컨트롤러에서이 작업을 수행하거나 블로그 서비스 (블로그 관리자)를 만들어 사용할 수 있습니다. 나는 서비스에 그 일을하는 것이 좋습니다 것입니다 :

당신의/번들/자원/설정/services.yml에 서비스를 정의

services 
    service.blog: 
    class: Your\Bundle\Service\BlogService 
    arguments: [@doctrine.orm.default_entity_manager] 

귀하의/번들/서비스/BlogService.php :

class BlogService 
{ 

    private $entityManager; 

    /* 
    * @param EntityManager $entityManager 
    */ 
    public function __construct($entityManager) 
    { 
     $this->entityManager = $entityManager; 
    } 

    /* 
    * @param integer $blogId 
    * 
    * @return Blog 
    */ 
    public function getBlogById($blogId) 

     return $this->entityManager 
        ->getRepository('AppBlogBundle:Blog') 
        ->find($blogId); 
    } 
} 

그리고 컨트롤러에 간단히 갈 수

$blogId = //however you get your blogId 
$blogEntry = //however you get your blogEntry 

$blogService = $this->get('service.blog'); 
$blog = $blogService->getBlogById($blogId); 

$blogEntry->setBlog($blog); 
+0

답변 해 주셔서 감사합니다, Cris. 그러나 if ($ blog = $ blogservice-> getBlogById ($ blogId)와 if ($ blog = $ doctrine-> getEntityManager-> getRepository ('...'))를 사용하여 BlogService와 컨트롤러를 사용하는 것의 차이점은 무엇입니까? -> find ($ blogId)) 두 경우 모두 컨트롤러의 블로그 존재 여부를 확인한 다음 $ blogEntry에 할당해야합니다.이 컨트롤러를 컨트롤러 클래스 외부에 숨겨서 컨트롤러를 가능한 작게 만들려고합니다. – Ris90

+0

컨트롤러의 코드 양이 좋다고 생각하고, 간결하고 명확하며 작업을 완료합니다. 서비스에서 getBlogById() 메서드를 사용하면 응용 프로그램에서 한 줄만 사용하여 다른 곳으로 다시 사용할 수 있다는 장점이 있습니다. –

+0

두 가지 접근법의 차이점은 서비스 옵션에는 코드를 반복 할 필요가 없다는 것입니다. 컨트롤러에서 직접 doctrine을 호출하면 동일한 작업을 다른 곳에서 다시 수행해야 할 때 복제해야합니다. 티 그는 $ doctrine-> getEntityManager() ... 코드 –

관련 문제