willdurand / Hateoas

A PHP library to support implementing representations for HATEOAS REST web services.
https://williamdurand.fr/Hateoas/
Other
1.04k stars 118 forks source link

Allow a relation to have an array of values #293

Open goetas opened 5 years ago

goetas commented 5 years ago

A relation link can contain multiple links.

See example case as in https://github.com/willdurand/Hateoas/issues/290#issuecomment-491450460

I think is a bad idea to give to relation providers access to object, probably can be avoided by still creating only one relation, but the allowing multiple links in it.

egonolieux commented 5 years ago

Replying to https://github.com/willdurand/Hateoas/issues/290#issuecomment-506225139 here.

I'm certainly willing to work on this. I can't say when however as I'm quite busy at this time.

For those interested in a "decent enough" workaround for the time being:

@Hateoas\Relation(
    "books",
    href="",
    attributes={"href": "expr(service('books_to_links_mapper').mapToLinks(object.getBooks(), 'book', { 'bookId': 'id' }))"},
    exclusion=@Hateoas\Exclusion(excludeIf="expr(object.getBooks() == [])")
)

It essentially overrides the href property using attributes, on which a service call can be made to convert the books to links. The arguments of mapToLinks are the books, the route name of an individual book and the properties needed for the route parameters.

This gives the following result:

"_links": {
    "books": {
        "href": [
            "http://book_1",
            "http://book_2",
            "http://book_3"
        ]
    }
}