jeudi 18 novembre 2021

Symfony manualy resolve dependencies [duplicate]

I use a command dispatcher pattern.

I have a resolver that match a given command with it's corresponding handler, like so:

class HandlerResolver
{
    public function resolve(CommandInterface $command): AbstractHandler
    {
        $handlerClass = preg_replace('/Command/', 'Handler', $command::class);
        return new $handlerClass();
    }
}

I want some of my handlers have services in their constructor eg:

abstract class AbstractHandler
{
    public function handle(CommandInterface $command): CommandResponse
    {
        $action = $command->getAction();
        $args = $command->getArgs();

        $response = call_user_func_array([$this, $action], $args);

        return (new CommandResponse())->wrap($response);
    }
}

class NotifierHandler extends AbstractHandler
{
    public function __construct(
        private SomeService $service,
    ) {
    }

    protected function notify()
    {
        // use my private service
    }
}

How can I use Symfony tools to detect and inject some declared services inside my new $handlerClass(), of course to be simpler all of my concrete handlers doesn't all have the same services as dependencies...

I hope it's clear !

Thanks for you time !

Aucun commentaire:

Enregistrer un commentaire