태그 보관물: symfony

symfony

Symfony2에서 번들과 관련된 파일 액세스 특히 Symfony \ Component \ Yaml \

Symfony2 앱의 라우팅 구성에서 다음과 같은 파일을 참조 할 수 있습니다.

somepage:
    prefix: someprefix
    resource: "@SomeBundle/Resources/config/config.yml"

컨트롤러 또는 다른 PHP 코드 내에서 번들과 관련된 파일에 액세스하는 방법이 있습니까? 특히 Symfony \ Component \ Yaml \ Parser 개체를 사용하여 파일을 구문 분석하려고하는데 해당 파일을 절대적으로 참조하고 싶지 않습니다. 기본적으로 이렇게하고 싶습니다.

$parser = new Parser();
$config = $parser->parse( file_get_contents("@SomeBundle/Resources/config/config.yml") );

Symfony \ Component \ Finder \ Finder 클래스를 확인했지만 그게 내가 찾고있는 것 같지 않습니다. 어떤 아이디어? 아니면 더 나은 방법을 완전히 간과하고 있습니까?



답변

사실이를 위해 사용할 수있는 서비스 인 커널 ( $this->get('kernel'))이 있습니다. 라는 메서드가 locateResource()있습니다.

예를 들면 :

$kernel = $container->getService('kernel');
$path = $kernel->locateResource('@AdmeDemoBundle/path/to/file/Foo.txt');


답변

Thomas Kelley의 대답은 훌륭하지만 작동하지만 종속성 주입을 사용하거나 코드를 커널에 직접 연결하고 싶지 않은 경우 FileLocator 클래스 / 서비스를 사용하는 것이 좋습니다.

$fileLocator = $container->get('file_locator');
$path = $fileLocator->locate('@MyBundle/path/to/file.txt')

$fileLocator의 인스턴스가 \Symfony\Component\HttpKernel\Config\FileLocator됩니다. $path파일의 전체 절대 경로가됩니다.

file_locator서비스 자체가 커널을 사용 하더라도 훨씬 더 작은 종속성입니다 (자신의 구현을 대체하는 것이 더 쉬움, 테스트 이중 사용 등).

종속성 주입과 함께 사용하려면 :

# services.yml

services:
    my_bundle.my_class:
        class: MyNamespace\MyClass
        arguments:
            - @file_locator

# MyClass.php

use Symfony\Component\Config\FileLocatorInterface as FileLocator;

class MyClass
{
    private $fileLocator;

    public function __construct(FileLocator $fileLocator)
    {
        $this->fileLocator = $fileLocator;
    }

    public function myMethod()
    {
        $path = $this->fileLocator->locate('@MyBundle/path/to/file.txt')
    }
}


답변

를 사용 하여 애플리케이션 $container->getParameter('kernel.root_dir')app폴더 를 가져 오고 원하는 파일로 디렉토리를 검색 할 수 있습니다.


답변

에있는 파일에서이를 수행 하려면 현재 파일의 전체 경로를 가져 오는 데 src/.../SomeBundle/...사용할 수 있습니다 __DIR__. 그런 다음 Resources/...경로를 추가하십시오.

$foo = __DIR__.'/Resources/config/config.yml';


답변