Search code examples
symfonyhateoas

Multiple links in Bazinga Hateoas with Symfony


I am using Bazinga Hateoas with Fosrest in one of my SF2 project.

In one of API call, I want to display link of friends with current user or user id supplied like this:

    {
        "_links": {
            "self": { "href": "/users/1" },
            "friends": [
              { "href": "/users/2" },
              { "href": "/users/3" },
            ]
        },
    }

I am using below code in Entity.User.yml file:

relations:
    -
      rel: self
      href:
        route: api_1_get_users
        parameters:
          id: expr(object.getId())
        absolute: true
    -  
      rel: expr(object.findFriends(object.getId()))
      href:
        route: api_1_get_users
        parameters:
          id: expr(object.getId())
        absolute: true

I have put "findFriends" method in repository but its not accessible inside yml file. I guess this is not the correct way of doing things.

I have gone through https://github.com/willdurand/Hateoas but not able to figure out how to do it. Please guide me how I can achieve this...

Any help would be much appreciated !

Please guide me how I can achieve this


Solution

  • This is how you work with @RelationProvider.

    /**
     * Note:
     * ====
     * RelationProvider takes the method name which returns the relations.
     * 
     * @Hateoas\RelationProvider("addRelations")
     */
    class LinkContainingResource
    {
        public function addRelations($object, ClassMetadataInterface $classMetadata)
        {
            /**
             * Important Note:
             * ===============
             * Relation is actually an Hateoas\Configuration\Relation object,
             * NOT \Hateoas\Configuration\Annotation\Relation
             */
            return [new Relation('relation_name', 'link1'),
                    new Relation('relation_name', 'link2'),
                    new Relation('relation_name', 'link3')];
        }
    }
    

    Json/Hal Result:

    {
      "_links": {
        "relation_name": [
          {"href": "link1"},
          {"href": "link2"},
          {"href": "link3"}
        ]
      }
    }