cura/api-platform-extras

API Platform 的包装类

1.1.2 2024-01-18 14:27 UTC

This package is auto-updated.

Last update: 2024-09-18 16:01:49 UTC


README

基于流行的库 API platform,此库在处理器/提供者接口之上添加了一个抽象层,可以扩展以实现自定义逻辑。

如果您需要为 API platform 实现自定义处理器/提供者,但又不想反复实现样板代码,则可以使用此库。此外,抽象类还支持 phpstan 模板。

在扩展抽象处理器时,您不需要扩展所有抽象方法,而只需扩展您实际想要支持的方法。如果您的资源只支持 POSTPATCH,则只需扩展 handlePostOperationhandleDeleteOperation。这也使您能够为每个 HTTP 方法创建单个处理器。

在扩展抽象提供者时,您可以自由扩展 provideCollectionprovideItem 函数。默认情况下,这些函数分别返回空数组和 null。如果您的应用程序有自定义逻辑以确定何时返回集合,则可以扩展 canProvideCollection 函数。如果它返回 true,则抽象提供者将调用 provideCollection 函数,否则将调用 provideItem 函数。

使用示例

自定义处理器的示例(支持所有 HTTP 方法)

<?php

declare(strict_types=1);

namespace App\Processor;

use ApiPlatform\Metadata\Delete;
use ApiPlatform\Metadata\Patch;
use ApiPlatform\Metadata\Post;
use ApiPlatform\Metadata\Put;
use DominikPeters\ApiPlatformExtras\AbstractProcessor;

final class CustomProcessor extends AbstractProcessor
{
    protected function supportsResource(mixed $resource, array $uriVariables, array $context): bool
    {
        // In the read world this would check whether $resource is an instance
        // of your API platform resource
        return $resource !== null;
    }
    
    protected function handlePostOperation($resource, Post $operation, array $uriVariables, array $context): object
    {
        // Custom persistence logic goes here
        return $resouce;
    }
    
    protected function handlePutOperation($resource, Put $operation, array $uriVariables, array $context): object
    {
        // Custom replacement logic goes here
        return $resouce;
    }
    
    protected function handlePatchOperation($resource, Patch $operation, array $uriVariables, array $context): object
    {
        // Custom update logic goes here
        return $resouce;
    }
    
    protected function handleDeleteOperation($resource, Delete $operation, array $uriVariables, array $context): object
    {
        // Custom deletion logic goes here
    }
}

自定义提供者的示例

<?php

declare(strict_types=1);

namespace App\Provider;

use ApiPlatform\Metadata\GetCollection;use ApiPlatform\Metadata\Operation;use DominikPeters\ApiPlatformExtras\AbstractProvider;

final class CustomProvider extends AbstractProvider
{
    protected function canProvideCollection(Operation $operation, array $uriVariables, array $context) : bool
    {
        if ($operation instanceof GetCollection) {
            return true;
        }
        
        // We can/should provide a collection if no uuid is given
        return !array_key_exists('uuid', $uriVariables);
    }
    
    protected function provideCollection(array $uriVariables,array $context) : array{
        // Custom collection fetch logic here
        return [];
    }
    
    protected function provideItem(array $uriVariables,array $context) : ?object{
        // Custom fetch logic here, return null if not found
        return null;
    }
}