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');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?