在 Symfony2中访问相对于捆绑包的文件

在 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 类,但我不认为这是我要找的。有什么想法吗?或许我完全忽略了一个更好的方法?

45576 次浏览

You can use $container->getParameter('kernel.root_dir') to get the app folder of your application, and browse your directories to the file you want.

If you want to do that in a file located in src/.../SomeBundle/... you can use __DIR__ to get the full path of the current file. Then append your Resources/... path to that like

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

As a matter of fact, there is a service you could use for this, the kernel ($this->get('kernel')). It has a method called locateResource().

For example:

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

Thomas Kelley's answer is good (and works!) but if you are using dependency injection and/or don't want to tie your code directly to the kernel, you're better off using 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 though the file_locator service itself uses the kernel, it's a much smaller dependency (easier to substitute for your own implementation, use test doubles, etc.)

To use it with dependency injection:

# 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')
}
}