Skip to main content

Using bitexpert/pathfinder with willdurand/hateoas

This blog post might be outdated!
This blog post was published more than one year ago and might be outdated!
· 2 min read
Stephan Hochdörfer
Head of IT Business Operations

When I began converting the unKonf API backend to make use of Adroit and Disco I wanted to give the willdurand/Hateoas a try to turn the API into a "real" HATEOAS REST web service. Since we use our Pathfinder component as a router it felt natural to use Pathfinder to generate the links for the relations between the different domain objects. Luckily the willdurand/hateoas is pretty flexible and allows to define custom Url Generators with a few lines of code:

$hateoas = \Hateoas\HateoasBuilder::create()
->setUrlGenerator(
null,
new \Hateoas\UrlGenerator\CallableUrlGenerator(
function ($route, array $parameters, $abs) {
// return url here
return '';
}
)
)
->build();

In case of Pathfinder the configuration looks like this:

$baseUrl = 'http://localhost/';
$router = new \bitExpert\Pathfinder\Psr7Router($baseUrl);
$router->setRoutes([
\bitExpert\Pathfinder\Route::create()
->from('/days/[:dayId]/sessions')
->to('sessions')
->accepting('GET'),
]);

$hateoas = \Hateoas\HateoasBuilder::create($seralizer)
->setCacheDir($hateoasCache)
->addMetadataDir($hateoasCache)
->setUrlGenerator(
null,
new \Hateoas\UrlGenerator\CallableUrlGenerator(
function ($route, array $parameters, $abs) use ($router) {
return $router->generateUri($route, $parameters);
}
)
)
->build();

The link relation configuration looks like this:

use Hateoas\Configuration\Annotation as Hateoas;

/**
* @Hateoas\Relation(
* "sessions",
* href = @Hateoas\Route(
* "sessionsPerDayRoute",
* parameters = {
* "dayId" = "expr(object.getId())"
* }
* )
* )
*/
class Day