【问题标题】:ApiPlatform/Symfony - Generate path for resourcesApiPlatform/Symfony - 为资源生成路径
【发布时间】:2020-07-20 14:17:36
【问题描述】:

我喜欢为 APiPlatform 资源生成 uri,这对我来说似乎很初级,但我似乎不知道怎么做。这就是我想要完成的:

鉴于下面的资源定义,我想根据资源类名称、操作类型和操作名称获取 url。

/**
 * @ApiResource(
 *     itemOperations={"GET"},
 *     collectionOperations={"GET"}
 * )
 */
class Customer
{
    // ... 
}
$path = $someApiPlatformService->getOperationPath(Customer::class, ApiPlatform\Core\Api\OperationType::COLLECTION, 'GET');

路径的预期值为/api/customers。

$itemId = 'someid';
$path = $someApiPlatformService->getOperationPath(Customer::class, ApiPlatform\Core\Api\OperationType::ITEM, 'GET', $itemId);

路径的预期值为/api/customers/someid。

【问题讨论】:

    标签: php symfony api-platform.com


    【解决方案1】:

    关于网址生成

    您的问题主要由 IriConverterInterface::getIriFromResourceClass() 方法处理。这是将 URL 转换为实体和将实体转换为 URL 的 api 平台核心服务。

    但是,它不使用操作名称,因为正如 here 解释的那样:

    默认情况下,API Platform 使用 itemOperations 中定义的第一个 GET 操作生成项目的 IRI,并使用 collectionOperations 中定义的第一个 GET 操作生成集合的 IRI

    部分解决方案

    既然 IriConverterInterface 还不够,你还需要

    1. 计算你的路由名称,例如与内部(即禁止,我现在不知道使用什么服务,但我猜它是路由命名空间中的一个接口)RouteNameGenerator::generate(),
    2. 然后将其传递给 UrlGeneratorInterface::generate() 方法,正如 Symfony here 所解释的那样
    $resourceNameAsArray = explode('\\', Customer::class);
    $resourceShortName = $resourceNameAsArray[count($resourceNameAsArray) -1];
    $routeName = ApiPlatform\Core\Bridge\Symfony\Routing\RouteNameGenerator::generate('GET', $resourceShortName, ApiPlatform\Core\Api\OperationType::COLLECTION);
    $path = $urlGenerator->generate($routeName);
    

    【讨论】:

    • 感谢您的回复。发布此问题后,我还深入研究了 api-platform/core 的内部结构,并发现了您描述的相同类/方法。不过,这似乎有点绕道,尤其是因为内部的 RouteNameGenerator 类。我仍然希望找到更直接的方式:) 如果没有,你的方式可能是要走的路。
    猜你喜欢
    • 2015-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-30
    • 1970-01-01
    相关资源
    最近更新 更多