Как создать сервис для класса и передать туда аргументы Symfony 4?

У меня есть класс
class ExistsChecker
{
    /**
     * @var Repository
     */
    private $repository;

    /**
     * @var UniqueEntity
     */
    private $uniqueEntity;

    public function __construct(
        UniqueEntityInterface $uniqueEntity,
        Repository $repository
    ) {
        $this->repository = $repository;
        $this->uniqueEntity = $uniqueEntity;
    }
}


Repository и UniqueEntityInterface - интерфейсы. У репозитория есть 3 реализации, а у UniqueEntityInterface - одна сущность

Я пишу так
user_exists_checker:
        class: App\ExistsChecker
        arguments:
            App\Repository\Repository: '@App\Repository\User\DoctrineUserRepository'
            App\Entity\UniqueEntityInterface: '@App\Entity\User'


А на выходе получаю
Cannot autowire service "user_exists_checker": argument "$repository" of method "App\ExistsChecker::__construct()" references interface "App\Repository\Repository" but no such service exists. You should maybe alias this interface to one of these existing services: "App\Repository\DoctrineRepository", "App\Repository\User\DoctrineUserRepository", "App\Repository\Workspace\DoctrineWorkspaceRepository".
  • Вопрос задан
  • 483 просмотра
Решения вопроса 1
BoShurik
@BoShurik Куратор тега Symfony
Symfony developer
https://symfony.com/doc/current/service_container/...

services:
    _defaults:
        autowire: true
        autoconfigure: true
        bind:
            App\Repository\Repository $cachedRepository: '@App\Repository\User\CachedUserRepository'

    App\Repository\Repository: '@App\Repository\User\DoctrineUserRepository'
    App\Entity\UniqueEntityInterface: '@App\Entity\User'

    user_exists_checker:
        class: App\ExistsChecker
        bind:
            App\Repository\Repository: '@App\Repository\User\ApiUserRepository'


Может пригодится, если несколько реализаций интерфейсов: https://symfony.com/blog/new-in-symfony-3-4-local-...

Чтобы переопределить реализацию интерфейса для конкретного сервиса
user_exists_checker:
    class: App\ExistsChecker
    bind:
        App\Repository\Repository: '@App\Repository\User\ApiUserRepository'


Можно переопределить интерфейс для определенного названия переменной https://symfony.com/blog/new-in-symfony-4-2-autowi...
_defaults:
        autowire: true
        autoconfigure: true
        bind:
            App\Repository\Repository $cachedRepository: '@App\Repository\User\CachedUserRepository'

В примере выше, если в конструкторе вместо App\Repository\Repository $repository будете использовать App\Repository\Repository $cachedRepository, то вам придет App\Repository\User\CachedUserRepository
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы