Using custom ParamConverter for POST Request in Sy

2019-08-05 14:33发布

I'm using Symfony 2.6 and the FOS Rest Bundle.

Param converters for PATCH , DELETE and GET requests work nicely and reduce the code in the controller actions. However for POST requests I have a problem. The default \Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter gets called every time. This results in an exception:

Unable to guess how to get a Doctrine instance from the request information.

I checked the \Sensio\Bundle\FrameworkExtraBundle\EventListener\ParamConverterListener and saw that it's always including the Doctrine param converter in the onKernelController method. From the documentation it seems that the doctrine param converter is automatically applied for all type hinted controller actions unless you set it to off:

sensio_framework_extra:
    request:
        converters: true
        auto_convert: false

I found a kind of hacky way to prevent this. The array of param converters to be applied will be indexed by the name of the type hinted argument in the controller method (which symfony gets by reflection). If I just name my param converter the same as this type hint then the default doctrine param converter will not be added to the list of param converters. For example:

     ...
     * @ParamConverter(
     *  "MyEntity",
     *  class="Foo\Bar\MyEntity",
     *  converter="my_custom_converter"
     * )
     *
     * @param MyEntity $myEntity
     * @return MyEntity
     */
    public function postMyEntityAction(MyEntity $myEntity)
    {

I sort of wrote this question as I was digging deeper into the code and I'm not even really sure what my question is anymore. I guess it's "Is it logical to apply multiple param converters?" or would also like to know if it's possible to turn off param converters for certain actions. Maybe my logic is completely wrong here and this isn't what param converters were intended for.

I'd appreciate any advice.

1条回答
你好瞎i
2楼-- · 2019-08-05 15:20

Alright, I realized where I was going wrong. It was a simple case of not returning true from my custom paramConverter apply method. If it does return true then the doctrine param converter won't be applied.

查看更多
登录 后发表回答