将服务注入服务

时间:2019-01-03 16:19:44

标签: php symfony symfony4

我试图在我创建的服务的构造函数中注入诸如entityManager之类的公共服务,但是我仍然遇到此错误:

函数App \ Services \ BillingInterface :: __ construct()的参数太少,第144行的/var/www/.../src/Controller/TestController.php中传递了0,而正好是1。 / strong>

在我的控制器中,服务正确注入了不同的方法,但是在我创建的服务中却没有注入到构造函数中。

我没有更改services.yaml中的任何内容,因为文档说autowire在Symfony 4.2中是自动的

PS:我最近从Symfony 4.1更新到4.2,我不确定,但我认为它以前可以工作。

也许图书馆没有正确更新,但是我没有发现任何错误。

Here are the informations for the service

服务代码:

#/src/Services/BillingInterface

namespace App\Services;

use Doctrine\ORM\EntityManagerInterface;

class BillingInterface {

    private $em;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->em = $entityManager;
    }

}

控制器代码:

namespace App\Controller;

use App\Services\BillingInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class TestController extends AbstractController {

    public function teest(EntityManagerInterface $entityManager)
    {
        $billing = new BillingInterface();
    }


}

如果我使用Controller的$entityManager参数实例化BillingInterface,它可以工作,但我希望将其直接注入BillingInterface类构造函数中。

最后,这是Symfony文档中写的内容:

// src/Service/MessageGenerator.php
// ...

use Psr\Log\LoggerInterface;

class MessageGenerator
{
    private $logger;

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

    public function getHappyMessage()
    {
        $this->logger->info('About to find a happy message!');
        // ...
    }
}

链接https://symfony.com/doc/current/service_container.html

章:将Services / Config注入服务

所以,我不知道我的服务出了什么问题。

谢谢您的回答。

1 个答案:

答案 0 :(得分:5)

由于您的BillingInterface是一项服务-您需要使用Symfony容器提供的其实例,而不是尝试自己实例化它。您的控制器需要注入此服务才能使用它:

namespace App\Controller;

use App\Services\BillingInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class TestController extends AbstractController
{
    /**
     * @var BillingInterface
     */
    private $billing;

    /**
     * @param BillingInterface $billing
     */
    public function __construct(BillingInterface $billing)
    {
        $this->billing = $billing;
    }

    public function teest(EntityManagerInterface $entityManager)
    {
        // Use $this->billing ... 
    }
}