简体   繁体   中英

How to get a RESTful response with sub-resource represented as uri using FOS Rest Bundle and Symfony2?

I am using Symfony2 with Doctrine and FOS Rest Bundle (which uses JMS serializer). There are two entities Father and Child :

<?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;
}

and

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;
}

There are routes :

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

And finally there is a controller with actions for these routes:

<?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;
    }
}

When I call GET /child/ I get the expected response:

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

Instead of nested response I would like to get an uri of Father resource, ie:

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

What is the best way to achieve this?

You can try with one of Hateoas bundles for example: BazingaHateoasBundle or FSCHateoasBundle . You can probably search more using http://knpbundles.com

You can use a "father" virtualProperty that uses your custom logic to return the value for "father" field.

See: JMSSerializer YAML config reference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM