Skip to content

Instantly share code, notes, and snippets.

@harikt
Last active December 27, 2019 06:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harikt/8671136 to your computer and use it in GitHub Desktop.
Save harikt/8671136 to your computer and use it in GitHub Desktop.
Aura.Router and Aura.Dispatcher
{
"require": {
"aura/router": "^3.0",
"aura/dispatcher": "^2.0",
"zendframework/zend-diactoros": "^2.2"
}
}
<?php
require __DIR__ . '/vendor/autoload.php';
use Aura\Dispatcher\Dispatcher;
use Aura\Router\RouterContainer;
use Zend\Diactoros\Response;
use Zend\Diactoros\ServerRequest;
class Blog
{
public function browse(ServerRequest $request)
{
$response = new Response();
$response->getBody()->write("Browse all posts!");
return $response;
}
public function read(ServerRequest $request, $id)
{
$id = (int) $request->getAttribute('id');
$response = new Response();
$response->getBody()->write("Read blog entry $id");
return $response;
}
public function edit(ServerRequest $request, $id)
{
$response = new Response();
$response->getBody()->write("Edit blog entry $id");
return $response;
}
}
$dispatcher = new Dispatcher;
$dispatcher->setObjectParam('controller');
$dispatcher->setMethodParam('action');
$dispatcher->setObject('blog', new Blog());
$routerContainer = new RouterContainer();
$map = $routerContainer->getMap();
$map->get('blog.browse', '/blog', 'blog::browse');
$map->get('blog.read', '/blog/{id}', 'blog::read');
$request = Zend\Diactoros\ServerRequestFactory::fromGlobals(
$_SERVER,
$_GET,
$_POST,
$_COOKIE,
$_FILES
);
$matcher = $routerContainer->getMatcher();
$route = $matcher->match($request);
if ($route) {
foreach ($route->attributes as $key => $val) {
$request = $request->withAttribute($key, $val);
}
list($controller, $action) = explode('::', $route->handler);
$params = [
'controller' => $controller,
'action' => $action,
'request' => $request,
'id' => $request->getAttribute('id'),
];
$response = $dispatcher($params);
// emit the response
foreach ($response->getHeaders() as $name => $values) {
foreach ($values as $value) {
header(sprintf('%s: %s', $name, $value), false);
}
}
http_response_code($response->getStatusCode());
echo $response->getBody();
} else {
echo "No route found";
}
@idezigns
Copy link

Any possibility of an example of this using Aura Route 3.x

@harikt
Copy link
Author

harikt commented Oct 30, 2017

@idezigns the router just need to change the way of instantiation. The rest will be the same I guess.

See @auraphp 3.x docs on the example http://auraphp.com/packages/3.x/Router/getting-started.html#1-4-1-5 . The handler will be the one that you may want to make use of.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment