简体   繁体   English

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

[英]Inject kernel.root_dir to entity constructor in Symfony2

i searh and read a lot of same question but ever i got the same error :/ 我搜索并阅读了很多相同的问题,但我得到了同样的错误:/

I create a service: 我创建了一个服务:

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

And i has this in T\\BackendBundle\\Entity\\Report: 我在T \\ BackendBundle \\ Entity \\ Report中有这个:

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

When i try to create new Report(); 当我尝试创建新的Report(); i receive this msg: 我收到这个消息:

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

Considerations: i know the services.yml is called, i has more services in this file and all work ok (Loginhandlers, etc), i only add one more (tbackend.entity.report) 注意事项:我知道services.yml被调用,我在这个文件中有更多服务,所有工作正常(Loginhandlers等),我只添加一个(tbackend.entity.report)

What is wrong with that? 这有什么问题? :( I dont know if need more for know about the problem. I follow symfony2 service container guide http://symfony.com/doc/master/book/service_container.html :(我不知道是否需要更多了解问题。我按照symfony2服务容器指南http://symfony.com/doc/master/book/service_container.html

Basically I try not to use DIR in the Entity when moving files 基本上我在移动文件时尽量不在实体中使用DIR

Ty

When instantiating a class, you use normal PHP. 实例化类时,使用普通的PHP。 Symfony isn't some magic that hooks into the instantiating process of PHP to automatically inject things in the constructor. Symfony并不是一种魔术,可以在PHP的实例化过程中自动注入构造函数中的东西。

If you want to get a service, you either have to inject the service in the class you need it or you have the containe rin the class (for instance, in the controller) and retrieve the service from the container. 如果您想获得服务,您必须在您需要的类中注入服务,或者您拥有容器(例如,在控制器中)并从容器中检索服务。

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

or: (which is a much better practice in all cases except from controllers) 或:(除控制器外,在所有情况下都是更好的做法)

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