繁体   English   中英

将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(); 我收到这个消息:

警告:缺少T \\ BackendBundle \\ Entity \\ Report :: __ construct()的参数1,在第62行的/var/www/test/t_study/src/T/BackendBundle/Entity/ReportRepository.php中调用并定义

注意事项:我知道services.yml被调用,我在这个文件中有更多服务,所有工作正常(Loginhandlers等),我只添加一个(tbackend.entity.report)

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

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

实例化类时,使用普通的PHP。 Symfony并不是一种魔术,可以在PHP的实例化过程中自动注入构造函数中的东西。

如果您想获得服务,您必须在您需要的类中注入服务,或者您拥有容器(例如,在控制器中)并从容器中检索服务。

$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"]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM