【问题标题】:How to get a RESTful response with sub-resource represented as uri using FOS Rest Bundle and Symfony2?如何使用 FOS Rest Bundle 和 Symfony2 获得以 uri 表示的子资源的 RESTful 响应?
【发布时间】:2013-11-27 18:12:12
【问题描述】:

我将 Symfony2 与 Doctrine 和 FOS Rest Bundle(它使用 JMS 序列化程序)一起使用。 有两个实体 父亲孩子

<?php

namespace Acme\Bundle\CoreBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Father
 *
 * @ORM\Table()
 * @ORM\Entity
 */
class Father {
    /**
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     **/
    private $id;

    /**
     * @ORM\Column(name="name", type="string", length=255)
     */
    protected $name;
}

namespace Acme\Bundle\CoreBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Child
 *
 * @ORM\Table()
 * @ORM\Entity
 */
class Child {
    /**
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     **/
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="Acme\Bundle\CoreBundle\Entity\Father")
     **/
    private $father;
}

路线

acme_test_child_all:
    defaults: { _controller: AcmeCoreBundle:Test:childAll }
    path:   /child/
acme_test_father_get:
    defaults: { _controller: AcmeCoreBundle:Test:fatherGet }
    path:   /father/{id}

最后有一个 控制器 对这些路由执行操作:

<?php

namespace Acme\Bundle\CoreBundle\Controller;

use FOS\RestBundle\Controller\Annotations as Rest;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class TestController extends Controller {
    /**
     * @Rest\View()
     */
    public function childAllAction() {
        $children = $this->getDoctrine()
            ->getRepository('AcmeCoreBundle:Child')
            ->findAll();

        return $children;
    }

    /**
     * @Rest\View()
     */
    public function fatherGetAction($id) {
        $father = $this->getDoctrine()
            ->getRepository('AcmeCoreBundle:Child')
            ->findById($id);

        return $father;
    }
}

当我调用 GET /child/ 时,我得到了预期的响应:

[
    {
        "id": 1,
        "father": {
            "id":1,
            "name":"Father"
        }
    }
]

我想获得父亲资源的 uri 而不是嵌套响应,即:

[
    {
        "id": 1,
        "father": "/father/1"
    }
]

实现这一目标的最佳方法是什么?

【问题讨论】:

    标签: php symfony doctrine-orm fosrestbundle jmsserializerbundle


    【解决方案1】:

    您可以尝试使用 Hateoas 捆绑包之一,例如:BazingaHateoasBundleFSCHateoasBundle。您可能可以使用http://knpbundles.com 进行更多搜索

    【讨论】:

    • FSCHateoasBundle 即将被弃用,取而代之的是 Hateoas 库及其捆绑包 (BazingaHateoasBundle)。
    【解决方案2】:

    您可以使用“父亲”virtualProperty,它使用您的自定义逻辑返回“父亲”字段的值。

    见: JMSSerializer YAML config reference

    【讨论】:

      猜你喜欢
      • 2019-03-04
      • 2017-08-28
      • 2015-12-09
      • 2017-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多