为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 YAML 中使用 API 平台过滤器?

如何在 YAML 中使用 API 平台过滤器?

PHP
三国纷争 2021-09-05 16:30:52
我正在使用 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在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{...}我希望你能提供帮助,我的问题得到了清楚的解释。如果没有,请告诉我,我会尽力为您提供更多详细信息。
查看完整描述

1 回答

?
慕桂英3389331

TA贡献2036条经验 获得超8个赞

我找到了解决我的问题的方法。看来 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和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']


    # ...

我刚刚通过使用(如我所说的)重要过滤器 ID为 GET 收集操作添加了过滤器。所以,这解决了我的问题。但是,如果有人有更好/更简单的解决方案,我很高兴知道。


查看完整回答
反对 回复 2021-09-05
  • 1 回答
  • 0 关注
  • 263 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号