Insert kernel.root_dir into constructor object in Symfony2

i searched and read a lot of questions but ever 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 have this in T \ BackendBundle \ Entity \ Report:

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

      

When I try to create a new Report (); I am getting this message:

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 service.yml is being called, I have more services in this file and everything is working fine (Loginhandlers etc.), I add another one (tbackend.entity.report)

What's wrong with this? :( I don't know if I need to know more about the problem. I am following the Symfony2 container maintenance instructions http://symfony.com/doc/master/book/service_container.html

Basically I try not to use DIR on the object when moving files

Tee

+3


source to share


1 answer


You are using regular PHP when instantiating the class. Symfony is not some kind of magic that intercepts the PHP creation process to automatically insert things into the constructor.

If you want to receive a service, you either need to inject the service into the class you need, or you have a class in the class (like a controller) and get the service from the container.

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

      



or: (which is much better practice in all cases except controllers)

class WhereINeedTheReport
{
    private $report;

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

      

services:
    # ...
    where_i_need_the_report:
        class: ...
        arguments: ["@tbackend.entity.report"]

      

+3


source







All Articles