5

首先,我想通知您,我已经阅读了有关我今天遇到的问题的文档,并且我还在 StackOverflow 和 Google 上进行了搜索,但没有找到合适的解决方案。

为了练习,我正在使用 Symfony 4 和 API 平台构建客户关系管理 API。我已经学到了很多关于 API 平台的知识,即使我可以使用注解来配置资源,我还是强迫自己使用 YAML 来了解更多信息。

所以,我有一个 Customer 资源,它有几个属性:idfirstnamelastnameemailAddresscompanycreatedAtupdatedAtowner。我的目标是在这个资源上添加一个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
{
...
}

我希望你能提供帮助,并且我的问题得到了清楚的解释。如果没有,请告诉我,我会尽力为您提供更多详细信息。

谢谢!

4

1 回答 1

9

我找到了解决我的问题的方法。看来 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:这里需要autowireandautoconfigure参数,否则会报错:

当设置了“父级”时,服务“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 收集操作添加了过滤器。所以,这解决了我的问题。如果有人有更好/更简单的解决方案,我很高兴知道。

屏幕截图:当 SearchFilter 就位时 API 的样子

于 2019-06-28T19:27:03.963 回答