dongpo7467 2015-05-21 19:25
浏览 98
已采纳

获取symfony中任何文件的绝对路径

I'm trying to follow the small tutorial here http://symfony.com/doc/current/components/finder.html but I'm just absolutely lost on how to actually find a file. I guess I have two problems to solve.

1) What's a good method in Symfony to determine the /path/to/src from say the controller?

2) How do I use Finder to get the absolute path to my desired file?

In a partial answer to 1 I'm aware of $this->get('kernel')->getRootDir() but that points to /path/to/app and I guess I could just add ../src to the end but I would like something a little cleaner.

I would prefer to crawl through subdirectories rather than specify just a single folder to look in.

Here's what I've tried

/* In this case the actual file exists in src/MyBundle/config/myFile.xml */
$finder = new Finder();

$finder->files()->name('myFile.xml')->in('/path/to/src');

Or I've also done.

$finder->files()->name('myFile.xml')->in('/path/to/src/MyBundle/config');

Finder throws an error if the directory doesn't exist. So I know there's not an error with my path string. But when I try to foreach($finder as $file) through the results or $finder->getIterator() I just end up with NULL every time.

Thanks.

  • 写回答

1条回答 默认 最新

  • dptn69182 2015-05-21 20:01
    关注

    The intent of the Finder component is to provide an easy way to iterate through files and directories on a disk. It is not intended to be used with only one file and if the path to that file is not known.

    In order to get directory the PHP file is located at you can use __DIR__. For example, if your code is in the Controller directory of your bundle

    echo __DIR__.'/../Resources/config/myFile.xml';
    

    You can use Finder if you want to iterate through all XML files in the config directory.

    $finder->files()->name('*.xml')->in(__DIR__.'/../Resources/config');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题