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

获取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 求帮我调试一下freefem代码
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图