简体   繁体   中英

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:

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

When i try to create new 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

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)

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

Basically I try not to use DIR in the Entity when moving files

Ty

When instantiating a class, you use normal PHP. Symfony isn't some magic that hooks into the instantiating process of PHP to automatically inject things in the constructor.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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