mardi 15 décembre 2020

How to create Chain of Responsibility in symfony

I'm trying to understand the chain of responsibillity in Symfony. I followid this example but i'm stuk at injecting the handler class in the client to run the chain. The problem is that I get this error:

Cannot autowire service "FileReader": argument "$handler" of method "__construct()" references class "AbstractHandler" but no such service exists. You should maybe alias this class to one of these existing services: "NameHandler", "DescriptionHandler".

I understand I cannot inject an abstract class like that, but i'm alo not sure how to get this working.

This is some PHP to give context, this code will not run.

abstract class AbstractHandler
{
    private AbstractHandler $nextHandler;

    public function setNext(AbstractHandler $handler): AbstractHandler
    {
        $this->nextHandler = $handler;

        return $handler;
    }

    public function handle(string $request): ?string
    {
        if ($this->nextHandler) {
            return $this->nextHandler->handle($request);
        }

        return null;
    }
}

class NameHandler extends AbstractHandler
{
    public function handle(string $request): ?string
    {
        if ($request === "name") {
            return "it's a name";
        }

        return parent::handle($request);
    }
}

class DescriptionHandler extends AbstractHandler
{
    public function handle(string $request): ?string
    {
        if ($request === "description") {
            return "it's a description";
        }

        return parent::handle($request);
    }
}

class FileReader
{
    private $handler;

    public function __construct(AbstractHandler $handler)
    {
        $this->handler = $handler;
    }

    public function findField(array $fields)
    {
        $fields = ["name"];

        foreach ($fields as $field) {
            echo $this->handler->handle($field); //it's a name
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire