2012-05-17 3 views
21

저는 심포니 2를 사용하고 있습니다. dev와 prod의 두 가지 설정이 있습니다. 엔티티 또는 모델 내부에서 어떤 것을 사용 하는지를 알아낼 수 있는지 알아야합니다.symfony 2에서 AppKernel 환경 변수에 액세스

내가 AppKernel.php에서 발견 된이 코드와 비슷한 뭔가를 찾고 있어요

:

$this->getEnvironment() 

나는 잘 될 것이라고이 전화를 커널을로드 할 수 있지만 내가 할 수있는 방법을 찾을 수없는 경우 이. 이것을 살펴 본 후에 심포니 이벤트는 커널을 반환 할 수 있지만이 이벤트를 캡처 할 방법이나 위치를 모르므로 getKernel()을 호출 할 수 있습니다. http://symfony.com/doc/current/book/internals.html

는 예를 들어,이 예제를 나열 :

사용 심포니 \ 구성 요소 \ HttpKernel \ 이벤트 \ FilterControllerEvent;

public function onKernelController(FilterControllerEvent $event) 
{ 
    $controller = $event->getController(); 
    // ... 

    // the controller can be changed to any PHP callable 
    $event->setController($controller); 
} 

이 코드 블록을 어디에 둘 것인지 명확하지 않습니다. 그것은 커널에 있어야한다고 생각합니다. 커널을 가지고 있다면이 문제가 발생하지 않을 것입니다.

제 질문은 커널에 설정된 서비스 또는 모델에서 'dev'또는 'prod'에 있는지 쉽게 판단 할 수 있습니다. 감사합니다.

답변

44

콘솔에서 생성 된 기본 엔티티 클래스는 아무 것도 상속하지 않습니다. 즉, 어떤 식 으로든 "ContainerAware"가 아닙니다.

일반적으로 말하면 나는 그들이 그렇게해야한다고 생각하지 않습니다. 나는에 따라 생각 당신이하고있는하지만 당신은 컨트롤러에서 몇 가지 기본적인 의존성 주입

으로이 문제를 해결할 수 있는지 :

$entity = new \Your\Bundle\Entity\Foo(
    $this->container->get('kernel')->getEnvironment() 
); 

그리고 SRC에서/당신의/번들/법인/Foo.php

private $env; 

public function __construct($env=null) 
{ 
    $this->env = $env; 
} 

이 기능을 사용할 수 있습니까?

P.S. 게시 한 이벤트 리스너는 임의의 클래스가 아닌 컨트롤러 용입니다.

+0

예, 심포니 2.6을 사용하고 – ContextSwitch

+0

을 리팩토링의 비트와 함께 잘 작동합니다 않았다, 감사합니다 그리고 나는해야만했다 : $ kernel = $ this-> container-> get ('kernel'); – Dominick

18

매개 변수로 가져올 수도 있습니다. \Symfony\Component\HttpKernel\Kernel 클래스를 살펴보면 모든 커널 매개 변수를 노출하는 getKernelParameters() 메서드를 찾을 수 있습니다.

/** 
* Returns the kernel parameters. 
* 
* @return array An array of kernel parameters 
*/ 
protected function getKernelParameters() 
{ 
    $bundles = array(); 
    foreach ($this->bundles as $name => $bundle) { 
     $bundles[$name] = get_class($bundle); 
    } 

    return array_merge(
     array(
      'kernel.root_dir' => realpath($this->rootDir) ?: $this->rootDir, 
      'kernel.environment' => $this->environment, 
      'kernel.debug' => $this->debug, 
      'kernel.name' => $this->name, 
      'kernel.cache_dir' => realpath($this->getCacheDir()) ?: $this->getCacheDir(), 
      'kernel.logs_dir' => realpath($this->getLogDir()) ?: $this->getLogDir(), 
      'kernel.bundles' => $bundles, 
      'kernel.charset' => $this->getCharset(), 
      'kernel.container_class' => $this->getContainerClass(), 
     ), 
     $this->getEnvParameters() 
    ); 
} 

그래서 services.yml 파일에 당신이 컨테이너 인식 클래스 동안 %kernel.environment%와 환경을 얻을 수 있습니다 당신은 수행하여 얻을 수 있습니다 : 물론

$this->getContainer()->getParameter('kernel.environment'); 

see Kernel.php class on github

+0

symfony의 다음 릴리스에 추가 된 매개 변수를 잊지 않도록'parent :: getKernelParameters()'메서드를 호출하는 것이 좋습니다 :) 'return array_merge (parent :: getKernelParameters() , array (...));' –

3

가 빠른있다 그리고 더러운 지구 적 방법 ...

function quickAndDirty() { 
    global $kernel; 

    if ($kernel->getEnvironment() == 'dev') { 
     // we're in dev mode 
    } 
} 

그것의 나쁜 악하고 당신이 그것을 사용 후 자신을 씻어야합니다,하지만 당신은 아마 상속 큰 기존의 코드베이스의 경우, 그것은 잠재적 인 리팩토링 악몽을 절약 할 수 있습니다.

물론

, 당신은 이러한 방법을 사용 후 자신과 함께 살 수 있는지, 당신에게 달려있다)

관련 문제