Api 平台 3 Symfony 6 自定义属性过滤器

问题描述 投票:0回答:2

我已经添加了 propertyFilter 以按属性过滤,但它与我想要的格式不匹配......实际上它是:properties[]=field1&properties[]=field2......我想要它像 properties=字段 1,字段 2,....

我尝试在 kernel_request(预读优先级)上设置事件侦听器以进行一些转换,但它不起作用,因为 uri 已经生成。

我怎样才能实现它?

编辑

我想在 ApiPlatform 的上下文中实施解决方案。

symfony filter api-platform.com symfony6
2个回答
0
投票

以下是如何实现此目标的示例:

1。在您的 Symfony 应用程序中创建自定义路由配置:

# config/routes/custom.yaml
custom:
  path: /custom/{properties}
  defaults:
    _controller: App\Controller\CustomController::index
  requirements:
    properties: '^[a-zA-Z0-9,_]+$'

此配置定义了一个带有占位符

properties
的新路由,对应字母、数字、逗号、下划线的任意组合。该路由映射到
CustomController::index
操作并处理转换后的请求。

2。定义

CustomController
类并实现索引动作:

// src/Controller/CustomController.php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;

class CustomController extends AbstractController
{
    public function index(Request $request)
    {
        $properties = explode(',', $request->attributes->get('properties'));

        // Now you have an array of properties that you can use to filter your data
        // ...

        // Forward the original request to the appropriate controller
        $controller = $request->attributes->get('_controller');
        $arguments = $request->attributes->get('_route_params');
        $arguments['properties'] = $properties;

        return $this->forward($controller, $arguments);
    }
}

此控制器操作将接收转换后的属性参数作为数组,您可以使用它来过滤数据。

3。更新您的应用程序代码以使用新路线:

// Before:
$response = $client->request('GET', '/data?propertyFilter=properties[]=field1&properties[]=field2');

// After:
$response = $client->request('GET', '/custom/field1,field2');

现在你可以捕获原始的URI,将属性参数转换成想要的格式,然后将请求传递给合适的控制器。通过使用路由配置是可能的。


0
投票

我找到了一种方法让它在 api 平台和实体的上下文中工作,我创建了一个序列化上下文生成器,记录在此处https://api-platform.com/docs/core/serialization/#changing-the -serialization-context-dynamically(Book 的示例)并且我更改函数 createFromRequest 中的属性:

public function createFromRequest(Request $request, bool $normalization, ?array $extractedAttributes = null): array
{
    $context = $this->decorated->createFromRequest($request, $normalization, $extractedAttributes);
    if (!empty($request->query->get('properties'))) {
        $fields = explode(',', $request->query->get('properties'));
        $context['attributes'] = array_values($properties);
    }
    
    return $context;
}
© www.soinside.com 2019 - 2024. All rights reserved.