'How to use dependency injection in validator constraints with Doctrine & Symfony

I'm working on an platform which contains lot of page with form and i'm looking for a way to inject (DI) service in my Entity/Constraint Validator. I tried many way, but never managed to do 100% what i wanted it.

Let me explain en detail : my stack : Php 8.0, Symfony 5.4, Doctrine 2

To make it simple, i will take the example of create page Form.

The form is build with a dedicated FormType (let's say DogType). The Entiy related to this FormType is Dog I'm using static loader to load constraints loadValidatorMetadata()

The field dog_race has a constraint ChoiceType. The data of choice should be filled with a method from a service AnimalManager, method getRaces. The constructor of this service is also using DI to get some other service such as Logger etc.

So, i know we can do something like that :

public static function loadValidatorMetadata(ClassMetadata $metadata)
{
    [...]
    $metadata->addPropertyConstraints('dog_race',
        [
            new Assert\Choice([
                'callback' => [DogManager::class, 'getRaces'],
                'message'  => 'doc.incorrect_race'
            ])
        ]
    )
}

But this callback works only with static method. If i'm not mistaken, we can use only static loader, php attribut and annotation, right ? But in all cases, i don't see how i can inject a service for the constraint.

My question is, how can i inject my service DogManager to be used in the constraint ? If not possible, any recommendation/alternative to do something similar ?

I have the feeling i have to create custom constraint just to be able to inject my service.. :(

Thanks



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source