Andrei Herford
Andrei Herford

Reputation: 18729

How to use Symfony container parameters in annotations?

Is it generally possible to use container parameters in method/class annotations in Symfony 5.3+?

For example one of my action methods uses a @ParamConverter annotation using the FOSRest RequestBodyParamConverter:

class SomeController extends AbstractController {   
    /**
     * @ParamConverter("post", converter="fos_rest.request_body")
     */
    public function sync(Request $request, Post $post): Response {
        ...
    }
}

Instead of explicitly specifying the the converter here, I would like to use a container parameter instead. However, this does not seem to work.

I have checked that the parameter is defined correctly:

$ php bin/console debug:container --parameters
...
my.post.converter     fos_rest.request_body

But I cannot use it:

/**
  * @ParamConverter("post", converter="%my.post.converter%")
  */

No converter named '%my.post.converter%' found for conversion of parameter 'post'.

I found other questions which indicate, that using parameters should be possible. At least when working with other annotations like @Route.

Is this a limitation of the @ParamConverter annotation (= a special feature of the @Route annotation), or is there anything wrong with my setup?

I know that there are other ways of specifying a different converter in this example. However, this is just an example and the question is, whether using a parameter here should be possible or if I made some error.

Upvotes: 0

Views: 401

Answers (1)

yivi
yivi

Reputation: 47329

Not all annotations are equal. Each has its own processor, and each annotation argument has different accepted inputs.

And the annotations simply enable some underlying component, so sometimes (probably most of the time) if you can use a container parameter in an annotation, it's because the underlying component supports using a container parameter for that argument (as is the case with the Routing component, that can be configured via other ways than annotations/attributes)


Using a container parameter on the question provided example would not be particularly useful, if at all.

That argument expects a service ID, and since those IDs are defined on the container configuration (the same place where you would configure the parameters), moving the definition to a parameter would gain one nothing.

If you want to have it "configurable", maybe use a custom service id that you could define as an alias to the real service, that way you can have multiple converters and alias the correct one via configuration.

Not convinced that that would be something useful in real life, but your application constraints might be altogether different.

Upvotes: 1

Related Questions