Why absolute path constants __DIR__ and __FILE__ should not be used in Symfony

时光毁灭记忆、已成空白 提交于 2019-12-04 03:08:51

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'

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

Aerendir

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!