在Symfony2应用程序的路由配置中,我可以引用这样的文件:
somepage:
prefix: someprefix
resource: "@SomeBundle/Resources/config/config.yml"
Run Code Online (Sandbox Code Playgroud)
有没有办法在控制器或其他PHP代码中访问相对于bundle的文件?特别是,我正在尝试使用Symfony\Component\Yaml\Parser对象来解析文件,我不想绝对引用该文件.基本上,我想这样做:
$parser = new Parser();
$config = $parser->parse( file_get_contents("@SomeBundle/Resources/config/config.yml") );
Run Code Online (Sandbox Code Playgroud)
我已经检查了Symfony\Component\Finder\Finder类,但我认为这不是我想要的.有任何想法吗?或者我可能完全忽略了这样做的更好方法?
gil*_*den 179
事实上,你可以使用一个服务,即kernel($this->get('kernel')).它有一个叫做的方法locateResource().
例如:
$kernel = $container->getService('kernel');
$path = $kernel->locateResource('@AdmeDemoBundle/path/to/file/Foo.txt');
Run Code Online (Sandbox Code Playgroud)
faz*_*azy 78
Thomas Kelley的答案很好(并且有效!)但是如果你使用依赖注入和/或不想将代码直接绑定到内核,那么最好使用FileLocator类/服务:
$fileLocator = $container->get('file_locator');
$path = $fileLocator->locate('@MyBundle/path/to/file.txt')
Run Code Online (Sandbox Code Playgroud)
$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')
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
44155 次 |
| 最近记录: |