Aji*_*e62 5 php api-platform.com symfony-4.3
首先,我想通知您,我已经阅读了有关今天遇到的问题的文档,我也在 StackOverflow 和 Google 上进行了搜索,但没有找到合适的解决方案。
我正在使用 Symfony 4 和 API 平台构建客户关系管理 API 以供练习。我已经学到了很多关于 API 平台的知识,即使我可以使用注解进行资源配置,我还是强迫自己使用 YAML 以了解更多信息。
所以,我有哪几种属性的客户资源:ID,姓名,姓氏,EMAILADDRESS,公司,createdAt,updatedAt和所有者。我的目标是在这个资源上添加一个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
Run Code Online (Sandbox Code Playgroud)
在resources/customer.yaml:
App\Entity\Customer:
collectionOperations:
get:
normalization_context:
groups: ['Customer:Get']
filters: ['app.my_filter']
Run Code Online (Sandbox Code Playgroud)
我打算做的是类似于以下的注释src/Entity/Customer.php:
# filters
app.my_filter:
parent: 'api_platform.doctrine.orm.search_filter'
tags: ['api_platform.filter']
autowire: false
autoconfigure: false
public: false
Run Code Online (Sandbox Code Playgroud)
我希望你能提供帮助,我的问题得到了清楚的解释。如果没有,请告诉我,我会尽力为您提供更多详细信息。
谢谢!
我找到了解决我的问题的方法。看来 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
Run Code Online (Sandbox Code Playgroud)
注0:在autowire和autoconfigure参数都在这里需要的,否则你会得到一个错误:
当设置了“parent”时,服务“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']
# ...
Run Code Online (Sandbox Code Playgroud)
我刚刚通过使用(如我所说的)重要过滤器 ID为 GET 收集操作添加了过滤器。所以,这解决了我的问题。但是,如果有人有更好/更简单的解决方案,我很高兴知道。
屏幕截图:当 SearchFilter 就位时 API 的样子