php - 如何在 YAML 中使用 API 平台过滤器?
问题描述
首先,我想通知您,我已经阅读了有关我今天遇到的问题的文档,并且我还在 StackOverflow 和 Google 上进行了搜索,但没有找到合适的解决方案。
为了练习,我正在使用 Symfony 4 和 API 平台构建客户关系管理 API。我已经学到了很多关于 API 平台的知识,即使我可以使用注解来配置资源,我还是强迫自己使用 YAML 来了解更多信息。
所以,我有一个 Customer 资源,它有几个属性:id、firstname、lastname、emailAddress、company、createdAt、updatedAt和owner。我的目标是在这个资源上添加一个SearchFilter(在 YAML 中)并将大部分属性添加为这个过滤器的属性。
我已经尝试过这里给出的解决方案:https ://github.com/api-platform/core/issues/1755 。问题是我无法让它工作。在 services.yaml 中,我看到您可以添加参数,但我不知道您可以在注释中找到什么等价物...
在config/services.yaml
:
# filters
app.my_filter:
parent: 'api_platform.doctrine.orm.search_filter'
tags: ['api_platform.filter']
autowire: false
autoconfigure: false
public: false
在resources/customer.yaml
:
App\Entity\Customer:
collectionOperations:
get:
normalization_context:
groups: ['Customer:Get']
filters: ['app.my_filter']
我打算做的是与此类似的注释src/Entity/Customer.php
:
/**
* @ApiResource
*
* [...]
*
* @ApiFilter(SearchFilter::class, properties={
* "firstname": "partial",
* "lastname": "partial",
* "emailAddress": "partial",
* "company": "partial"
* })
*/
class Customer
{
...
}
我希望你能提供帮助,并且我的问题得到了清楚的解释。如果没有,请告诉我,我会尽力为您提供更多详细信息。
谢谢!
解决方案
我找到了解决我的问题的方法。看来 API 平台文档毕竟离答案并不太远!在资源配置文件中尝试了一段时间后,我终于决定给该services.yaml
文件一个机会。我在这个 github 问题上得到了很大的帮助。所以,这就是我所做的。
第 1 步 -在services.yaml
:
# filters
app.customer_resource.search_filter:
parent: 'api_platform.doctrine.orm.search_filter'
arguments: [ { 'firstname': 'partial', 'lastname': 'partial', 'emailAddress': 'partial', 'owner.emailAddress': 'exact' } ]
tags: [ { name: 'api_platform.filter', id: 'customer.search_filter' } ]
autowire: false # required, explained below
autoconfigure: false # required, explained below
注意0:这里需要autowire
andautoconfigure
参数,否则会报错:
当设置了“父级”时,服务“app.customer_resource.search_filter”上的属性“autowire”/“autoconfigure”不能从“_defaults”继承。将您的子定义移动到单独的文件或在 [...] 中显式定义此属性(在资源“[...]”中加载)。
注 1:我注意到这里最重要的元素是“tags”参数的“id”元素。在寻找解决方案时,我发现了,这表明您必须提供过滤器 ID 才能使其正常工作。请在第 2 步中亲自查看。vendor/api-platform/core/src/Swagger/Serializer/DocumentationNormalizer::getFilter()
第 2 步 -在您的资源配置文件中(我的是在config/resources/customer.yaml
)
App\Entity\Customer:
collectionOperations:
get:
filters: ['customer.search_filter']
# ...
我刚刚使用(就像我说的)重要的过滤器 ID 为 GET 收集操作添加了过滤器。所以,这解决了我的问题。但如果有人有更好/更简单的解决方案,我很高兴知道。
推荐阅读
- c# - 赶上一个新添加的项目
- moodle - 在系统级别将用户分配给学生角色
- azure - 天蓝色云中的 Automation Anywhere 社区版
- quire-api - 检索 Quire API 的访问令牌 - unsupported_grant_type
- angular - Angular 应用程序在电子中打开,但不在浏览器中
- lettuce - 生菜中 thenAcceptAsync 的用例是什么
- c# - 如何使用 Ajax 以数组格式将多个图像从 MVC 视图发送到控制器?
- sql - 我想将包含范围的数字列表转换为仅数字列表
- sql - 选择具有聚合的多个列
- django - Django Rest Framework,TypeError:__init__() 接受 1 个位置参数,但给出了 2 个