访问相对于Symfony2中的捆绑包的文件 [英] Accessing Files Relative to Bundle in Symfony2

查看:54
本文介绍了访问相对于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 \ Finder类,但是我认为这不是我想要的.有任何想法吗?还是我完全忽略了一种更好的方法?

解决方案

事实上,有一种服务可用于此目的,即内核($this->get('kernel')).它具有一种称为 locateResource() 的方法. /p>

例如:

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

In a Symfony2 app's routing configuration, I can refer to a file like this:

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

Is there any way to access a file relative to the bundle within a controller or other PHP code? In particular, I'm trying to use a Symfony\Component\Yaml\Parser object to parse a file, and I don't want to refer to that file absolutely. Essentially, I want to do this:

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

I've checked out the Symfony\Component\Finder\Finder class, but I don't think that's what I'm looking for. Any ideas? Or maybe I'm completely overlooking a better way of doing this?

解决方案

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');

这篇关于访问相对于Symfony2中的捆绑包的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆