Created
December 12, 2013 03:24
-
-
Save alganet/7922753 to your computer and use it in GitHub Desktop.
Smallest HATEOAS sample in the world [citation needed]. Work in Progress!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Respect\Rest\Router; | |
$r3 = new Router(); | |
$routes = []; | |
$routes['singleAuthor'] = $r3->any('/authors/*', 'MySingleAuthorClass'); | |
$routes['singlePost'] = $r3->any('/posts/*', 'MySinglePostClass'); | |
$routes['postsList'] = $r3->any('/posts', 'MyPostsListClass'); | |
$routes['archives'] = $r3->any('/authors/*/posts', 'MyArchivesClass'); | |
$routes['singleAuthor']->trough( | |
function ($author) use ($routes) { | |
$author['_links'] = [ | |
'archives' => [ | |
'href' => $routes['archives']->createUri($author['id']), | |
'title' => "Archives for $author['name']" | |
], | |
'dc:image' => [ | |
'href' => $author['profile_image_url'] | |
] | |
]; | |
return $author; | |
} | |
); | |
$routes['singlePost']->trough( | |
function ($post) use ($routes) { | |
$post['_links'] = [ | |
'collection' => [ | |
'href' => $routes['postsList']->createUri(), | |
'title' => "All Posts" | |
], | |
'author' => [ | |
'href' => $routes['singleAuthor']->createUri($post['author']['id']), | |
'title' => "Archives for $post['author']['name']" | |
] | |
]; | |
return $post; | |
} | |
); | |
$routes['allPosts']->trough( | |
function ($posts) use ($routes) { | |
$itemLinks = []; | |
foreach ($posts as $post) { | |
$links[] = [ | |
'href' => $routes['singlePost']->createUri($post['id']), | |
'title' => "$post['title']" | |
]; | |
} | |
$posts['_links']['item'] = $itemLinks; | |
return $posts; | |
} | |
); | |
$r3->always( | |
'Accept', | |
array( | |
'application/json' => $jsonEncoder = function ($data) { | |
header('Content-Type: application/json'); | |
return json_encode($data); | |
}, | |
'.json' => $jsonEncoder | |
) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment