【问题标题】:How to inject a repository inside a service?如何在服务中注入存储库?
【发布时间】:2018-01-23 08:57:00
【问题描述】:

我正在使用 Symfony 制作简单的应用程序。我在这里配置了服务

services:
app.service.comments_service:
    class: AppBundle\Service\CommentsService
    autowire: true

app.service.projects_service:
    class: AppBundle\Service\ProjectService
    autowire: true
app.service.files_service:
        class: AppBundle\Service\FilesService
        autowire: true
app.service.users_service:
            class: AppBundle\Service\UserService
            autowire: true

我的服务使用存储库(例如cmets服务使用cmets存储库)这里是CommentsService的构造函数

属性

    private $entityManager;
    private $session;
    private $manager;
    private $commentsRepository;

构造函数:

public function __construct(
    EntityManagerInterface $entityManager,
    Session $session,
    ManagerRegistry $manager,CommentsRepository $commentsRepository)
{
    $this->entityManager = $entityManager;
    $this->session = $session;
    $this->manager = $manager;
    $this->commentsRepository = $commentsRepository;
}

当我尝试运行我的应用程序时出现此错误

PHP 致命错误:未捕获 Symfony\Component\DependencyInjection\Exception\AutowiringFailedException:无法自动装配服务“AppBundle\Repository\CommentsRepository”:方法“Doctr”的参数“$em” ine\ORM\EntityRepository::__construct()" 必须有一个类型提示或明确地给出一个值。 无法自动装配服务“app.service.cmets_service”:方法“AppBundle\Service\CommentsService::__construct()”的参数“$cmetsRepository”引用类“AppBundle\Repository\CommentsRepos” itory" 但不存在这样的服务。在 C:\xampp\htdocs\WINbetTaskManager\vendor\symfony\symfony\src\Symfony\Component\DependencyInjection\Compiler\AutowirePass.php:285

有什么办法可以解决这个问题吗?

【问题讨论】:

  • Autowire 有很多限制,这就是其中之一。您需要使用工厂来创建存储库(基本上是 EntityManager::getRepository(Comment::class) 您可以搜索详细信息并单独定义存储库服务。我认为 autowire 应该选择它们。
  • @Cerad 我相信这应该是一个答案,而不是评论。虽然赞成:)
  • @svgrafov 谢谢,虽然我知道存储库服务是如何工作的,但我对自动装配本身并没有做太多,所以我真的不知道是否会出现其他问题。换句话说,这更像是一个猜测而不是一个答案。

标签: php symfony dependency-injection


【解决方案1】:

所以我做了一些实验,这似乎奏效了:

// services.yml
AppBundle\Repository\CommentsRepository:
    factory: 'doctrine.orm.entity_manager:getRepository'
    arguments: ['AppBundle\Entity\Comments']

这应该为自动装配提供足够的信息来注入存储库。

【讨论】:

    猜你喜欢
    • 2012-08-26
    • 2018-08-15
    • 2020-06-06
    • 2020-08-01
    • 2017-12-05
    • 1970-01-01
    • 2015-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多