2013-04-16 3 views
0

내가 엔티티 클래스 내부에 넣어 다음과 같은 코드가 있습니다엔티티에서 서비스에 액세스

$filesystem = $this->container->get('knp_gaufrette.filesystem_map')->get('amazon'); 
$filesystem->write($this->file , $this->name, true); 

그러나이 항상의 오류 발생 :이 어떤 생각을

Notice: Undefined property: MySite\UserBundle\Entity\ProfilePicture::$container in /Users/Mike/Sites/MySite/src/MySite/MainBundle/Entity/Document.php line 98 

을 이유 경우? 엔티티에서 서비스 컨테이너에 액세스하려면 어떻게합니까?

나는 추상 클래스 내에서 이것을 넣어했습니다

abstract class Document 
{ 

...... 
} 

답변

0

레거시 환경에서는 ContainerAwareInterface를 구현하는 엔터티에 컨테이너를 자동으로 주입하는 doctrine eventlistener를 만들었습니다. 그것으로 최소한의 노력으로 일부 "레거시 엔티티"와 작업 할 수 있습니다.

Symfony ControllerResolver은 콘테이너 대신 컨트롤러에 컨테이너를 주입하는 것과 같습니다.

<?php 

namespace Acme\DemoBundle\Doctrine; 

use Doctrine\ORM\Event\LifecycleEventArgs; 
use JMS\DiExtraBundle\Annotation as DI; 
use Symfony\Component\DependencyInjection\ContainerAware; 
use Symfony\Component\DependencyInjection\ContainerAwareInterface; 
use Symfony\Component\DependencyInjection\ContainerInterface; 


/** 
* adds some nice features to more easy entity utilization 
* 
* @DI\Service 
* @DI\Tag("doctrine.event_listener", attributes = {"event" = "postLoad"}) 
*/ 
class ContainerAwareListener extends ContainerAware 
{ 

    /** 
    * @DI\InjectParams({ 
    *  "container" = @DI\Inject("service_container"), 
    * }) 
    */ 
    public function __construct(ContainerInterface $container = null){ 
     $this->setContainer($container); 
    } 

    /** 
    * After object is loaded, listener inject the container 
    * 
    * @param LifecycleEventArgs $args 
    */ 
    public function postLoad(LifecycleEventArgs $args) 
    { 
     $entity = $args->getEntity(); 
     if($entity instanceof ContainerAwareInterface){ 
      $entity->setContainer($this->container); 
     } 
    } 
} 

엔티티가 containerawareinterface를 구현해야하고 필요한 서비스 setContainer 얻을 수있다()에있어서, 상기 서비스는 JMSDIExtrabundle으로 정의되지만 services.yml에서 정의 될 수있다.

많은 사람들이 엔티티가 가능한 한 많이 의존하지 않아야하기 때문에 이것은 나쁜 습관이라고 제안합니다. 그러나 극한치 비율 (또는 극단적 인 마감 시간 :-)에서) 이것은 훌륭합니다.

+0

Entity listener를 사용 해본 적이 있습니까? – adit

+0

나는 당신이 의미하는 것을 이해하지 못했다. 그것은 엔티티 청취자이다 :) –

0

엔티티 데이터 모델입니다 만 데이터를 포함해야합니다.

대신 종속성 삽입을 사용하여 리스너 또는 관리자 서비스를 만드십시오.

+1

좋은 충고이지만 약간 마른 체형입니다. 제발, OP 정보 및 코드를 제공하십시오 :) – DonCallisto

+0

@akluth 것은이 Document 클래스 performUpload()라는 메서드를 가지고 있으며이 메서드 내부에 내가 실제로 업로드를 수행하는 곳입니다 – adit