为什么绝对路径常量 __DIR__ 和 __FILE__ 不应该在 Symfony 中使用 [英] Why absolute path constants __DIR__ and __FILE__ should not be used in Symfony

查看:24
本文介绍了为什么绝对路径常量 __DIR__ 和 __FILE__ 不应该在 Symfony 中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 SensioLabs Insight 来控制我的代码质量.

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)

但是如果分析的代码包含 __DIR____FILE__ PHP 魔术常量,SLInsight 会发出警告:

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

__DIR____FILE__ 常量可能与 Symfony 资源覆盖系统发生冲突.

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

如何使用这个常量会导致与 Symfony 的冲突?

How usage of this constants can causes conflicts with Symfony?

我怎样才能在我的代码中避免它们?

And how can I avoid them in my code?

推荐答案

在文件上传类的情况下,你大概可以忽略这个错误信息.但在其他情况下,最好使用 Symfony 文件定位器而不是硬编码文件路径.例如:

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');

代替:

$path = __DIR__.'/../../../src/Acme/AppBundle/Resources/config/services.xml'

这篇关于为什么绝对路径常量 __DIR__ 和 __FILE__ 不应该在 Symfony 中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆