我是Symfony (5.3)的新手,我希望扩展RequestBodyParamConverter (FOSRestBundle 3.0.5)来创建REST。将@ParamConverter注释与RequestBodyParamConverter一起使用可以很好地工作。但是,我想创建一个自定义转换器,它与RequestBodyParamConverter完成完全相同的工作,外加一些额外的工作。
我最初的猜测是简单地扩展RequestBodyParamConverter并在@ParamConverter注释中提供我的自定义子类。但是,RequestBodyParamConverter被定义为final,因此不能扩展.
将RequestBodyParamConverter / fos_rest.request_body_converter注入自定义转换器类(参见下面的示例)也失败,因为找不到服务。我认为这是因为它被定义为一个private
因此,我的最后一个想法是在我的自定义转换器类中创建一个RequestBodyParamConverter。虽然这是可行的,但我不知道这是否解决这个问题的正确方法。通过这种方式创建两次RequestBodyParamConverter。当然,这没有什么特别之处,但这是Symfony解决这个问题的方法,还是有其他解决方案?
示例:
在自定义转换器类中注入RequestBodyParamConverter
class MyParamConverter implements ParamConverterInterface {
protected $parentConverter;
public function __construct(ParamConverterInterface $parentConverter) {
$this->parentConverter = $parentConverter;
}
public function apply(Request $request, ParamConverter $configuration): bool {
doExtraWork();
return $this->parentConverter->apply(...);
}
}
// config/services.yaml
My\Project\MyParamConverter:
tags:
- { name: request.param_converter, converter: my_converter.request_body }
arguments:
# both fails since service is not found
$parentConverter: '@FOS\RestBundle\Request\RequestBodyParamConverter'
# OR
$parentConverter: '@fos_rest.request_body_converter'在自定义转换器类中创建RequestBodyParamConverter
class MyParamConverter implements ParamConverterInterface {
protected $parentConverter;
public function __construct(...parameters necessary to create converter...) {
$this->parentConverter = new RequestBodyParamConverter(...);
}
...
}发布于 2021-08-10 17:46:10
Symfony提供了一种实现装饰注册服务的方法
要使用它,您需要在容器中注册的FOS服务id。
要获得它,可以使用以下命令
symfony console debug:container --tag=request.param_converter检索要重写的服务的Service ID。
然后,您可以配置您的服务来装饰FOS one。
My\Project\MyParamConverter:
decorates: 'TheIdOf_FOS_ParamConverterService'
arguments: [ '@My\Project\MyParamConverter.inner' ] # <-- this is the instance of fos service也许您需要将tags添加到这个声明中,我不确定。
如果你面临错误请告诉我。
https://stackoverflow.com/questions/68727506
复制相似问题