php – Add more links to _links in HAL entity-ThrowExceptions

Exception or error:

I’m using mezzio-hal (v3) with the following HAL config:

[
    '__class__' => RouteBasedResourceMetadata::class,
    'resource_class' => Handler\PersonEntity::class,
    'route' => 'list.persons',
    'extractor' => ClassMethodsHydrator::class,
],
[
    '__class__' => RouteBasedCollectionMetadata::class,
    'collection_class' => Handler\PersonCollection::class,
    'collection_relation' => 'persons',
    'route' => 'list.persons',
],

This is my collection class:

class PersonCollection extends Paginator
{
}

This is my entity class:

class PersonEntity
{
    private $id;
    private $name;

    public function getId() : int
    {
        return $this->id;
    }

    public function setId(int $id) : self
    {
        $this->id = $id;
        return $this;
    }

    public function getName() : string
    {
        return $this->name;
    }

    public function setName(string $name) : self
    {
        $this->name = $name;
        return $this;
    }
}

This is my HAL building command:

$halResource = $this->getResourceGenerator()->fromObject($personCollection, $request);

And at least this is my output:

{
    "_total_items": 1,
    "_page": 1,
    "_page_count": 1,
    "_links": {
        "self": {
            "href": "/api/persons?page=1"
        }
    },
    "_embedded": {
        "persons": [
            {
                "id": 1,
                "name": "example",
                "_links": {
                    "self": {
                        "href": "/api/persons/1"
                    }
                }
            }
        ]
    }
}

What I want to know: Is it possible to add more links to every entity in my collection, e.g. to add a link to an endpoint for a list of contact information, and if so, how can I do this? I want to get this output:

"_links": {
    "self": {
        "href": "/api/persons/1"
    },
    "contacts": {
        "href": "/api/persons/1/contacts"
    }
}
How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *