API 平台自定义get操作

API Plateform custom get operation

我正在尝试使用 API 平台构建电子商务网站。

由于我将 JWT 身份验证与 LexikJWTAuthenticationBundle 结合使用,因此我很难让用户获得令牌。

我想访问用户的购物车

我通过自定义 post 操作成功添加到购物车。

<?php

namespace App\Controller;

use App\Entity\Article;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;


class AddToCart extends AbstractController
{
    private $em;

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

    public function __invoke(Article $data)
    {
        $user = $this->getUser();
        $user->addCart($data);
        $this->em->flush();
        return $user->getCart();
    }
}

我正在尝试使用相同的方式,但有一个获取请求

namespace App\Controller;


use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;


class GetCart extends AbstractController
{
    public function getCart()
    {
        $user = $this->getUser();
        return $user->getCart();
    }
}

<?php

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiResource;
use App\Repository\UserRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * @ORM\Entity(repositoryClass=UserRepository::class)
 * @ApiResource(
 *     itemOperations={
 *          "get",
 *          "put",
 *          "get_cart"={
 *               "method"="GET",
 *               "path"="/cart",
 *               "controller"=App\Controller\GetCart,
 *          },
 *     }
 * )
 */
class User implements UserInterface
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=180, unique=true)
     */
    private $username;

    /**
     * @ORM\Column(type="json")
     */
    private $roles = [];

    /**
     * @var string The hashed password
     * @ORM\Column(type="string")
     */
    private $password;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $email;

    /**
     * @ORM\ManyToMany(targetEntity=Article::class)
     */
    private $cart;


    /**
     * @return Collection|Article[]
     */
    public function getCart(): Collection
    {
        return $this->cart;
    }

    public function addCart(Article $cart): self
    {
        if (!$this->cart->contains($cart)) {
            $this->cart[] = $cart;
        }

        return $this;
    }

    public function removeCart(Article $cart): self
    {
        $this->cart->removeElement($cart);

        return $this;
    }
}

知道我做错了什么吗?

您是否尝试使用自定义 DataProvider 并注入安全性而不是使用控制器?


use Symfony\Component\Security\Core\Security;
use ApiPlatform\Core\DataProvider\ItemDataProviderInterface;
use ApiPlatform\Core\DataProvider\RestrictedDataProviderInterface;
use ApiPlatform\Core\DataProvider\SerializerAwareDataProviderInterface;
use ApiPlatform\Core\DataProvider\SerializerAwareDataProviderTrait;

class UserDataProvider implements ItemDataProviderInterface, RestrictedDataProviderInterface, SerializerAwareDataProviderInterface
{
    use SerializerAwareDataProviderTrait;
    public const OPERATION_NAME = "get_cart";
    private $security;

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

    public function supports(string $resourceClass, string $operationName = null, array $context = []): bool
    {
        return User::class === $resourceClass && self::OPERATION_NAME === $operationName;
    }

    public function getItem(string $resourceClass, $id, string $operationName = null, array $context = []): ?TableDuplication
    {
        dump($this->security->getUser(), $this->security->getToken()); die();
        // Do what you need
    }
}

$this->security->getUser() 将 return 您的用户并且 $this->security->getToken() 将 return 所有关于您的令牌

这是文档:https://api-platform.com/docs/core/data-providers/#custom-item-data-provider

使用自定义控制器不会关闭 api 平台的内置服务(DataProvider、(De)Serializer、DataPersister)。 使用内置的 DataProvider,您无法在没有 ID 的情况下进行项目操作。您的 GetCart 控制器不需要内置的 DataProvider,因此您可以将其关闭:

 * @ORM\Entity(repositoryClass=UserRepository::class)
 * @ApiResource(
 *     itemOperations={
 *          "get",
 *          "put",
 *          "get_cart"={
 *               "method"="GET",
 *               "path"="/cart",
 *               "controller"=App\Controller\GetCart,
 *               "read"=false,
 *          },
 *     }
 * )
 */
class User implements UserInterface
// ...