将 kernel.root_dir 注入 Symfony2 中的实体构造函数

Inject kernel.root_dir to entity constructor in Symfony2

我搜索并阅读了很多相同的问题,但我遇到了同样的错误:/

我创建了一个服务:

parameters:
    tbackend.report.class: T\BackendBundle\Entity\Report
services:
    tbackend.entity.report:
        class:  %tbackend.report.class%
        arguments: ["%kernel.root_dir%"]

我在 T\BackendBundle\Entity\Report 中有这个:

public function __construct($rootDir){
    $this->rootDir = $rootDir;
}

当我尝试创建新的 Report() 时;我收到这条信息:

Warning: Missing argument 1 for T\BackendBundle\Entity\Report::__construct(), called in /var/www/test/t_study/src/T/BackendBundle/Entity/ReportRepository.php on line 62 and defined

注意事项:我知道调用了 services.yml,我在此文件中有更多服务并且一切正常(登录处理程序等),我只添加一个 (tbackend.entity.report)

这有什么问题? :( 我不知道是否需要更多了解这个问题。我遵循 symfony2 服务容器指南 http://symfony.com/doc/master/book/service_container.html

基本上我在移动文件时尽量不在实体中使用DIR

实例化 class 时,您使用正常 PHP。 Symfony 并不是挂钩到 PHP 的实例化过程中以自动在构造函数中注入东西的魔法。

如果你想得到一个服务,你要么必须在你需要的 class 中注入服务,要么你有容器在 class 中(例如,在控制器中)并从容器中检索服务。

$report = $this->container->get('tbackend.entity.report');

或:(除了控制器之外,这在所有情况下都是更好的做法)

class WhereINeedTheReport
{
    private $report;

    public function __construct(Report $report)
    {
        $this->report = $report;
    }
}
services:
    # ...
    where_i_need_the_report:
        class: ...
        arguments: ["@tbackend.entity.report"]