Why absolute path constants __DIR__ and __FILE__ s

2020-07-06 05:48发布

I use SensioLabs Insight to control my code quality.

For a simple file upload, I have to get the absolute path of my uploads directory:

protected function getUploadRootDir()
{
    // the absolute directory path where uploaded
    return __DIR__.'/../../../../web/'.$this->getUploadDir();
}

Code directly coming from official documentation (How to handle file uploads with Doctrine)

But SLInsight raises a warning if the code analysed contains __DIR__ or __FILE__ PHP magic constants:

__DIR__ and __FILE__ constants may conflict with the Symfony resource overriding system.

How usage of this constants can causes conflicts with Symfony?

And how can I avoid them in my code?

3条回答
手持菜刀,她持情操
2楼-- · 2020-07-06 06:06

Well, this is actually something that SensioLabs Insight does not handles properly. It warns against using the constants because of the resource overriding system, but in many cases, these constants are used in places which are unrelated to the resource overriding system (and this is probably the case for your code here). So you can ignore the warning in this case

查看更多
做个烂人
3楼-- · 2020-07-06 06:13

In the case of the file upload class, you can probably ignore this error message. But in other cases, it's better o use the Symfony file locator instead of hardcoding file paths. For example:

$path = $this->get('kernel')->locateResource('@AppBundle/Resources/config/services.xml');

Instead of:

$path = __DIR__.'/../../../src/Acme/AppBundle/Resources/config/services.xml'
查看更多
一夜七次
4楼-- · 2020-07-06 06:24

If you are creating a third-party bundle and want to locate some resources, the (good) solution proposed by @Javier is not applicable as it throws an exception:

ServiceNotFoundException in ContainerBuilder.php line 816:
You have requested a non-existent service "kernel".

In this case the solution is to use $this->getPath(), a method inherited by the BundleNameBundle from the Symfony\Component\HttpKernel\Bundle\Bundle class.

This returns the same result of realpath(__DIR__).

So doing $this->getPath() . '/Resources/config/doctrine/mappings' is the same as realpath(__DIR__ . '/Resources/config/doctrine/mappings').

Originally proposed here.

查看更多
登录 后发表回答