小编Rxb*_*z18的帖子

将服务注入服务

我试图在我创建的服务的构造函数中注入像entityManager这样的公共服务,但我一直有这个错误:

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

在我的控制器中,服务是以不同的方法正确注入的,但在我创建的服务中,它不是在构造函数中注入的.

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

PS:我最近从Symfony 4.1更新到4.2,我不确定,但我认为它之前有效.

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

以下是该服务的信息

服务代码:

#/src/Services/BillingInterface

namespace App\Services;

use Doctrine\ORM\EntityManagerInterface;

class BillingInterface {

    private $em;

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

}
Run Code Online (Sandbox Code Playgroud)

控制器代码:

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();
    }


}
Run Code Online (Sandbox Code Playgroud)

如果我使用$entityManagerController的参数实例化BillingInterface ,它可以工作,但我希望它直接在BillingInterface类构造函数中注入.

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

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

use Psr\Log\LoggerInterface;

class MessageGenerator
{
    private $logger;

    public function __construct(LoggerInterface $logger) …
Run Code Online (Sandbox Code Playgroud)

php symfony symfony4

-2
推荐指数
1
解决办法
155
查看次数

标签 统计

php ×1

symfony ×1

symfony4 ×1