Access package related files in Symfony2

In the Symfony2 application routing configuration, I can reference the following file:

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

Is there a way to access the file relative to the package in the controller or other PHP code? In particular, I am trying to use the Symfony \ Component \ Yaml \ Parser object to parse a file, and I do not want to reference this file completely. Essentially, I want to do this:

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

I checked the Symfony \ Component \ Finder \ Finder class, but I don’t think what I am looking for. Any ideas? Or maybe I completely ignore the best way to do this?

+81
php symfony
Sep 28 2018-11-11T00:
source share
4 answers

In fact, there is a service for this, the kernel ( $this->get('kernel') ). It has a locateResource() method.

For example:

 $kernel = $container->getService('kernel'); $path = $kernel->locateResource('@AdmeDemoBundle/path/to/file/Foo.txt'); 
+175
Sep 28 '11 at 17:23
source share

Thomas Kelly's answer is good (and it works!), But if you use dependency injection and / or don't want to bind your code directly to the kernel, you'd better use the FileLocator class / service:

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

$fileLocator will be an instance of \Symfony\Component\HttpKernel\Config\FileLocator . $path will be the full, absolute path to the file.

Even if the file_locator service file_locator uses the kernel, it is a much lesser dependency (it’s easier to replace your own implementation, use test twins, etc.).

To use it when injecting dependencies:

 # 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') } } 
+79
Jul 09 '14 at 14:28
source share

You can use $container->getParameter('kernel.root_dir') to get the app folder of your application and view your directories in the desired file.

+6
Sep 28 '11 at 15:42
source share

If you want to do this in a file located in src/.../SomeBundle/... , you can use __DIR__ to get the full path to the current file. Then add the path Resources/... to whatever you like

 $foo = __DIR__.'/Resources/config/config.yml'; 
+4
Sep 28 '11 at 16:08
source share



All Articles