为什么绝对路径常量 __DIR__ 和 __FILE__ 不应在 Symfony 中使用
Why absolute path constants __DIR__ and __FILE__ should not be used in Symfony
我使用SensioLabs Insight来控制我的代码质量。
对于简单的文件上传,我必须获取上传目录的绝对路径:
protected function getUploadRootDir()
{
// the absolute directory path where uploaded
return __DIR__.'/../../../../web/'.$this->getUploadDir();
}
直接来自官方文档的代码(How to handle file uploads with Doctrine)
但如果分析的代码包含 __DIR__
或 __FILE__
PHP 魔法常量,SLInsight 会发出警告:
__DIR__
and __FILE__
constants may conflict with the Symfony resource overriding system.
这个常量的使用如何导致与 Symfony 的冲突?
如何在我的代码中避免它们?
嗯,这实际上是 SensioLabs Insight 没有正确处理的事情。
由于资源覆盖系统,它警告不要使用常量,但在许多情况下,这些常量用于与资源覆盖系统无关的地方(您的代码可能就是这种情况)。所以你可以忽略这种情况下的警告
在文件上传的情况下class,您可以忽略此错误消息。但在其他情况下,最好使用 Symfony 文件定位器而不是硬编码文件路径。例如:
$path = $this->get('kernel')->locateResource('@AppBundle/Resources/config/services.xml');
而不是:
$path = __DIR__.'/../../../src/Acme/AppBundle/Resources/config/services.xml'
如果您正在创建一个 third-party 包并想要定位一些资源,@Javier 提出的(好的)解决方案不适用,因为它会引发异常:
ServiceNotFoundException in ContainerBuilder.php line 816:
You have requested a non-existent service "kernel".
在这种情况下,解决方案是使用 $this->getPath()
,一种由 BundleNameBundle
从 Symfony\Component\HttpKernel\Bundle\Bundle
class.
继承的方法
这 returns 与 realpath(__DIR__)
.
相同的结果
这样做 $this->getPath() . '/Resources/config/doctrine/mappings'
与 realpath(__DIR__ . '/Resources/config/doctrine/mappings')
相同。
最初提议.
我使用SensioLabs Insight来控制我的代码质量。
对于简单的文件上传,我必须获取上传目录的绝对路径:
protected function getUploadRootDir()
{
// the absolute directory path where uploaded
return __DIR__.'/../../../../web/'.$this->getUploadDir();
}
直接来自官方文档的代码(How to handle file uploads with Doctrine)
但如果分析的代码包含 __DIR__
或 __FILE__
PHP 魔法常量,SLInsight 会发出警告:
__DIR__
and__FILE__
constants may conflict with the Symfony resource overriding system.
这个常量的使用如何导致与 Symfony 的冲突?
如何在我的代码中避免它们?
嗯,这实际上是 SensioLabs Insight 没有正确处理的事情。 由于资源覆盖系统,它警告不要使用常量,但在许多情况下,这些常量用于与资源覆盖系统无关的地方(您的代码可能就是这种情况)。所以你可以忽略这种情况下的警告
在文件上传的情况下class,您可以忽略此错误消息。但在其他情况下,最好使用 Symfony 文件定位器而不是硬编码文件路径。例如:
$path = $this->get('kernel')->locateResource('@AppBundle/Resources/config/services.xml');
而不是:
$path = __DIR__.'/../../../src/Acme/AppBundle/Resources/config/services.xml'
如果您正在创建一个 third-party 包并想要定位一些资源,@Javier 提出的(好的)解决方案不适用,因为它会引发异常:
ServiceNotFoundException in ContainerBuilder.php line 816:
You have requested a non-existent service "kernel".
在这种情况下,解决方案是使用 $this->getPath()
,一种由 BundleNameBundle
从 Symfony\Component\HttpKernel\Bundle\Bundle
class.
这 returns 与 realpath(__DIR__)
.
这样做 $this->getPath() . '/Resources/config/doctrine/mappings'
与 realpath(__DIR__ . '/Resources/config/doctrine/mappings')
相同。
最初提议