问题描述
我使用 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 资源覆盖系统发生冲突.
如何使用这个常量会导致与 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 中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!