订阅者在 get 方法上添加过滤器

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

我想知道是否可以在订阅者的某个 GET 调用上自动添加过滤器? 我正在使用 api_platform 5.4。

我已经使用 POST 方法的订阅者来根据连接的用户添加默认值。因此,我想根据连接的人过滤数据。

class FiltreCodeOrgaSubscriber implements EventSubscriberInterface
{
    /**
     * Entity Manager
     *
     * @var Entity Manager
     */
    protected $em;

    /**
     * @var security
     */
    protected $security;

    public function __construct(EntityManagerInterface $em, Security $security)
    {
        $this->em = $em;
        $this->security = $security;
    }

    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::VIEW => [
                ['setCodeOrga', EventPriorities::PRE_VALIDATE],
            ],
            KernelEvents::CONTROLLER_ARGUMENTS => [
              ['addCodeOrga', EventPriorities::PRE_WRITE],
            ]
        ];
    }

    public function addCodeOrga(ControllerArgumentsEvent $event) {
        $event->getRequest()->query->set('codeOrga', 777);
    }
    public function setCodeOrga(ViewEvent $event) {
        $maClasse = $event->getControllerResult();
        $methode = $event->getRequest()->getMethod();
        $user = $this->security->getUser();
        if (!$user) {
            throw new \Exception('Subscriber : Erreur lors de la récupération du code agent');
        }

        if (
            (
                $maClasse instanceof CodifRecrutement
                || $maClasse instanceof Etablissement
            )
            &&
            (
                $methode === 'POST' ||
                $methode === 'PUT'
            )
        )
        {
            var_dump('test1');
            $maClasse->setCodeOrga(intval($user->getCodeorga()));
        }
    }
}

但是结果并不好

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

在 API Platform 5.4 中,您可以使用自定义 Doctrine ORM 扩展自动向特定 GET 调用添加过滤器。您需要创建一个自定义 Doctrine 存储库并在那里应用过滤器。

  1. 为您的实体创建一个自定义存储库(假设其名为
    YourEntity
    ):
// src/Repository/YourEntityRepository.php

namespace App\Repository;

use Doctrine\ORM\EntityRepository;

class YourEntityRepository extends EntityRepository
{
    public function findByCodeOrga($codeOrga)
    {
        $qb = $this->createQueryBuilder('e');
        $qb->andWhere('e.codeOrga = :codeOrga');
        $qb->setParameter('codeOrga', $codeOrga);

        return $qb->getQuery()->getResult();
    }
}
  1. 在您的实体中配置存储库:
// src/Entity/YourEntity.php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\YourEntityRepository")
 */
class YourEntity
{
    // ... your entity definition
}

现在,当您对

YourEntity
发出 GET 请求时,您可以传递
codeOrga
参数来过滤结果。

注意:进行这些更改后,请确保您的数据库架构是最新的:

php bin/console doctrine:schema:update --force

这样,您就拥有了一个专用存储库,其中包含基于

codeOrga
进行过滤的自定义方法。根据您的实体和要求调整存储库和方法名称。


0
投票

感谢您的回复,但我希望找到一个更通用的解决方案。对多个实体有效。而且调用 API 时不需要输入。 这就是为什么我更多地关注订阅者方面。

© www.soinside.com 2019 - 2024. All rights reserved.