php DataProvider -API平台上的getSubresource

ut6juiuv  于 2023-04-28  发布在  PHP
关注(0)|答案(2)|浏览(197)

我想使用subresourceDataProvider来更改数据库中的一些数据。但当我这样做的时候,它进入了一个无限循环?如何阻止?

<?php
namespace App\DataProvider;

use ApiPlatform\Core\DataProvider\SubresourceDataProviderInterface;

class MessageDataProvider implements SubresourceDataProviderInterface
{
    private $subresourceDataProvider;

    public function __construct(SubresourceDataProviderInterface $subresourceDataProvider)
    {
        $this->subresourceDataProvider = $subresourceDataProvider;
    }
    public function getSubresource(string $resourceClass, array $identifiers, array $context, string $operationName = null)
    {
        return $this->subresourceDataProvider->getSubresource($resourceClass, $identifiers, $context, $operationName);
    }
}
b4wnujal

b4wnujal1#

MessageDataProvider类实现了SubresourceDataProviderInterface,它也是构造函数中的一个参数- symfony可能会试图通过将MessageDataProvider放入构造函数中来自动连接SubresourceDataProviderInterface。但是为了将MessageDataProvider放入构造函数中,它必须首先构建一个这种类型的示例。为此,需要调用MessageDataProvider构造函数。.无限循环就是这样产生的。
如果您打算注入一个SubresourceDataProvider的实体,您可以显式配置MessageDataProvider服务。链接到文档

b4lqfgs4

b4lqfgs42#

我在这个链接上找到了解决方案
https://github.com/api-platform/core/issues/2816#issuecomment-494579509

<?php

namespace App\DataProvider;

use ApiPlatform\Core\DataProvider\RestrictedDataProviderInterface;
use ApiPlatform\Core\DataProvider\SubresourceDataProviderInterface;
use App\Entity\Note;

class NoteSubresourceDataProvider implements RestrictedDataProviderInterface, SubresourceDataProviderInterface
{
    private $alreadyInvoked = false;
    private $subresourceDataProvider;

    public function __construct(SubresourceDataProviderInterface $subresourceDataProvider)
    {
        $this->subresourceDataProvider = $subresourceDataProvider;
    }

    public function getSubresource(string $resourceClass, array $identifiers, array $context, string $operationName = null)
    {
        $this->alreadyInvoked = true;

        $collection = $this->subresourceDataProvider->getSubresource($resourceClass, $identifiers, $context);

        return $collection;
    }

    public function supports(string $resourceClass, string $operationName = null, array $context = []): bool
    {
        return !$this->alreadyInvoked && Note::class === $resourceClass;
    }
}

编辑:我用SubresourceDataProviderInterface做了两个例子
www.example. com
https://github.com/aratinau/api-platform-pagination#eighth-example-use-querybuilder-in-subresource

相关问题