php - 使用 JMSSerializer 序列化的 Symfony 4 FOSRestBundle

标签 php symfony symfony4 fosrestbundle jms-serializer

我正在使用 Symfony 4 和 FOSRestBundle 构建 API。我有非常基本的关系:

实体:User.php

/**
* @ORM\Entity(repositoryClass="App\Repository\UserRepository")
*/
class User
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     * @JMS\Groups({"onlyId"})
     */
    private $id;

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

    //...

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\UserProduct", mappedBy="user", orphanRemoval=true)
     */
    private $userProducts;

实体:UserProduct.php

/**
* @ORM\Entity(repositoryClass="App\Repository\UserProductRepository")
*/
class UserProduct
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     * @JMS\Groups({"onlyId"})
     */
    private $id;

    //...

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="userProducts")
     * @JMS\Groups({"onlyId"})
     */
    private $user;

配置:fos_rest.yaml

fos_rest:
    body_converter:
        enabled: true
    view:
        view_response_listener: 'force'
        formats:
            json: true
    routing_loader:
        default_format: json
#    param_fetcher_listener:  true
#    allowed_methods_listener:  true
#    routing_loader: true
#    view:
#        view_response_listener:  true
#    exception:
#        codes:
#            App\Exception\MyException: 403
#        messages:
#            App\Exception\MyException: Forbidden area.
    format_listener:
        rules:
            - { path: ^/api, prefer_extension: true, fallback_format: json, priorities: [ json, html ] }
            - { path: ^/login_check, stop: true }
            - { path: ^/register, stop: true }

起初,当我发布用户 ID 和 JSON 数据时,我无法POST UserProduct 将 JSON 发送到端点,因为它抛出它需要一个 entity 的实例。 , 不是 integer或者我发送的任何内容。我通过本教程解决了这个问题 -> https://medium.com/@maartendeboer/using-the-symfony-serializer-with-doctrine-relations-69ecb17e6ebd

它使用 Symfony 序列化程序。我得到的是 circular reference返回时出错 View的 FOSRestBundle。在这一点上我知道 circular reference使用 JMS Serializer 工具可以很好地处理错误,并在我的 postUserProductAction 中使用它 Controller :

POST 产品并处理 circular reference我使用此 Controller (使用教程中自定义编写的反序列化方法反序列化发布的 JSON,将其插入数据库,然后在 JMS 序列化程序及其组的帮助下返回Response(不是 View )):

class UserProductController extends FOSRestController
    {
    /**
     * @Rest\Route("/api/product", name="userProduct")
     *
     *
     * @Method("POST")
     *
     * @param Request $request
     * @param SerializerInterface $serializer
     * @return Response
     * @throws \InvalidArgumentException
     */
    public function postUserProductAction(Request $request, SerializerInterface $serializer): View
    {
        $userProduct = $serializer->deserialize($request->getContent(), UserProduct::class, 'json');
        dump($userProduct);
        $em = $this->getDoctrine()->getManager();
        $em->persist($userProduct);
        $em->flush();

        $userProduct = $this->JMSSerializeWithGroups($userProduct,array('onlyId'));
        return new View($userProduct, Response::HTTP_OK);
    }
}

    /**
     * @param $entity
     * @param array $groupArray
     * @return mixed|string
     */
    public function JMSSerializeWithGroups($entity, Array $groupArray)
    {
        $JMSserializer = SerializerBuilder::create()->build();
        $entity = $JMSserializer->serialize( $entity, 'json', SerializationContext::create()->setGroups($groupArray));
        return $entity;
    }

我得到的响应很好且清晰:

{
    "id": 100,
    "user": {
        "id": 9
    }
}

但是好像有很多不必要的步骤。此外,如果我选择这种方法,我需要自己将 JMS 序列化添加到我的每个 Controller (GET、PUT 等)。

所以我的问题是为什么 FOSRestBundle 默认不使用 JMS 进行渲染 View ,正如它在其文档中所说的那样(如果已安装和注册)?我是否应该将它添加到某个地方以便 FOSRestBundle 识别它?也许如果可以的话,我一开始就不需要使用 Symfony Serializer?我想我可能会迷失在所有 Symfony 4 升级中。

谢谢!

最佳答案

由于我没有得到任何建议,所以我坚持使用我发布的相同解决方案。我会留下它以防有人需要它,因为它是一个完整的工作示例。

干杯

关于php - 使用 JMSSerializer 序列化的 Symfony 4 FOSRestBundle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49982802/

相关文章:

symfony - 如何获取symfony2/symfony3中的 bundle 列表?

php - 在 symfony 中使用参数执行 sql 请求时出现语法错误?

php - 输入标签中的换行符,来自 mysql 的数据

php - 存储当前日期时,应该在 web 应用程序中设置还是在数据库中设置?

php - 使用sftp上传文件时如何修复PHP curl错误CURLE_SSH(79)

symfony - 如何覆盖其他包中 FOSUserBundle 的架构文件

symfony - 基于 FOSUserBundle 和 bootstrap,登录模式窗口无法正常工作

php - 在 Symfony 中重定向回两步

php - Symfony 邮件程序原始内容很奇怪,包含 =20 =3D =

php - MYSQL 搜索脚本 php 的错误结果