Skip to content

[Service Container] The AutowireCallable attribute does not work #20294

@lkolndeep

Description

@lkolndeep

Hello Folks,

I tried to use in an example the AutowireCallable attribute:
https://symfony.com/doc/6.4/service_container.html#generating-adapters-for-functional-interfaces

Here, my code:

The interface:

interface MessageFormatterInterface
{
    public function format(string $message, array $parameters): string;
}

My service:

class MessageUtils
{
    public function format(string $message, array $parameters): string
    {
        $stringParam = '';
        if (count($parameters) > 0) {
            foreach($parameters as $element)
                $stringParam .= $element . ', ';
        }

        return strtoupper($message) . ' ' . $stringParam;
    }
}

My method in a controller:

#[Route('/service/message-utils', name: 'app_service_message_utils')]
public function messageUtils(MessageFormatterInterface $formatter): Response
{
    $formattedMessage = $formatter->format('Hello my friends!', ['parameter1', 'parameter2', 'parameter3', 'parameter4']);
    dd($formattedMessage);

    return new Response('Message Utils');
}

When I try this, an error occurs:

Cannot autowire argument $formatter of "App\Controller\ServiceController::messageUtils()": it references interface "App\Service\MessageFormatterInterface" but no such service exists. Did you create a class that implements this interface?

When I add the implements on the MessageUtils service:

class MessageUtils implements MessageFormatterInterface
{
    public function format(string $message, array $parameters): string
    {
        $stringParam = '';
        if (count($parameters) > 0) {
            foreach($parameters as $element)
                $stringParam .= $element . ', ';
        }

        return strtoupper($message) . ' ' . $stringParam;
    }
}

the AutowireCallable attribute works well and the dd($formattedMessage); in the controller gives me this:
"HELLO MY FRIENDS! parameter1, parameter2, parameter3, parameter4, "

Regards,

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions