如何从 Symfony 4 获取项目目录
How to get project directory from Symfony 4
我需要的是工程目录或者symfony的public目录。
use App\Kernel;
class FileReader
{
public function __construct(
Kernel $kernel
)
{
var_dump ($kernel->getProjectDir());
}
}
问题是我无法将内核注入我的class。
在post中有几件对我来说很奇怪的事情。
首先,我得到这个错误:
Cannot autowire service "App\Utils\Lotto\FileReader": argument "$kernel" of method "__construct()" references class "App\Kernel" but no such service exists. Try changing the type-hint to one of its parents: interface "Symfony\Component\HttpKernel\HttpKernelInterface", or interface "Symfony\Component\HttpKernel\KernelInterface".
其次,我没有来自 PHPStorm 自动完成的 KernelInterface,这些接口仅适用于没有 getProjectDirectory
方法的 HttpKernelInterface。
如何读出 /var/www/myproject
或 /var/www/myproject/public/
?
你不应该注入你的内核,而是只注入你需要的。在这种情况下,它是项目目录,可通过 config/services.yaml 中的服务定义使用参数 %kernel.project_dir%:
services:
App\Utils\Lotto\FileReader:
arguments:
$projectDirectory: "%kernel.project_dir%"
然后调整你的class构造函数:
public function __construct(string $projectDirectory) {
$this->directory = $projectDirectory;
}
作为奖励,您可以通过定义全局 "bind" 参数使该目录自动可用于您的所有服务:
services:
_defaults:
bind:
$projectDirectory: "%kernel.project_dir%"
根据该定义,每个服务都可以在其 __construct() 中使用变量 $projectDirectory,而无需显式定义它。
我需要的是工程目录或者symfony的public目录。
use App\Kernel;
class FileReader
{
public function __construct(
Kernel $kernel
)
{
var_dump ($kernel->getProjectDir());
}
}
问题是我无法将内核注入我的class。
在
首先,我得到这个错误:
Cannot autowire service "App\Utils\Lotto\FileReader": argument "$kernel" of method "__construct()" references class "App\Kernel" but no such service exists. Try changing the type-hint to one of its parents: interface "Symfony\Component\HttpKernel\HttpKernelInterface", or interface "Symfony\Component\HttpKernel\KernelInterface".
其次,我没有来自 PHPStorm 自动完成的 KernelInterface,这些接口仅适用于没有 getProjectDirectory
方法的 HttpKernelInterface。
如何读出 /var/www/myproject
或 /var/www/myproject/public/
?
你不应该注入你的内核,而是只注入你需要的。在这种情况下,它是项目目录,可通过 config/services.yaml 中的服务定义使用参数 %kernel.project_dir%:
services:
App\Utils\Lotto\FileReader:
arguments:
$projectDirectory: "%kernel.project_dir%"
然后调整你的class构造函数:
public function __construct(string $projectDirectory) {
$this->directory = $projectDirectory;
}
作为奖励,您可以通过定义全局 "bind" 参数使该目录自动可用于您的所有服务:
services:
_defaults:
bind:
$projectDirectory: "%kernel.project_dir%"
根据该定义,每个服务都可以在其 __construct() 中使用变量 $projectDirectory,而无需显式定义它。