A
A
Alexey Verkhovtsev2019-04-01 16:41:04
symfony
Alexey Verkhovtsev, 2019-04-01 16:41:04

How to create a service for a class and pass Symfony 4 arguments there?

I have a class

class ExistsChecker
{
    /**
     * @var Repository
     */
    private $repository;

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

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

Repository and UniqueEntityInterface are interfaces. Repository has 3 implementations and UniqueEntityInterface has one entity
I write like this
user_exists_checker:
        class: App\ExistsChecker
        arguments:
            App\Repository\Repository: '@App\Repository\User\DoctrineUserRepository'
            App\Entity\UniqueEntityInterface: '@App\Entity\User'

And the output is
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".

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BoShurik, 2019-04-01
@seftomsk

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'

May come in handy if there are multiple interface implementations: https://symfony.com/blog/new-in-symfony-3-4-local-...
To override an interface implementation for a particular service
user_exists_checker:
    class: App\ExistsChecker
    bind:
        App\Repository\Repository: '@App\Repository\User\ApiUserRepository'

You can override the interface for a specific variable name https://symfony.com/blog/new-in-symfony-4-2-autowi...
_defaults:
        autowire: true
        autoconfigure: true
        bind:
            App\Repository\Repository $cachedRepository: '@App\Repository\User\CachedUserRepository'

In the example above, if App\Repository\Repository $repositoryyou use instead of in the constructor App\Repository\Repository $cachedRepository, you will getApp\Repository\User\CachedUserRepository

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question