Skip to content

Instantly share code, notes, and snippets.

@graphis
Forked from harikt/router-middleware.php
Created May 26, 2020 19:19
Show Gist options
  • Save graphis/e693957cd62079ff0caf5874f59ffc10 to your computer and use it in GitHub Desktop.
Save graphis/e693957cd62079ff0caf5874f59ffc10 to your computer and use it in GitHub Desktop.
Conduit router middleware example
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use Phly\Conduit\Middleware;
use Phly\Http\Server;
$app = new Middleware();
$router = new \Aura\Router\Router(
new \Aura\Router\RouteCollection(new \Aura\Router\RouteFactory),
new \Aura\Router\Generator
);
$dispatcher = new \Aura\Dispatcher\Dispatcher(array(), 'controller', 'action');
$app->pipe(function ($request, $response, $next) use ($router, $dispatcher) {
$path = $request->getUri()->getPath();
$route = $router->match($path, $request->getServerParams());
if (! $route) {
return $next();
}
$params = $route->params;
$params['request'] = $request;
$params['response'] = $response;
$result = $dispatcher->__invoke($params);
if ($result instanceof \Psr\Http\Message\ResponseInterface) {
$response = $result;
} else {
$response = $response->write($result)->end();
}
return $response;
});
$router->add('homepage', '/')
->addValues(array('controller' => 'homepage'));
$router->add('blog.browse', '/blog')
->addValues(array('controller' => 'blog.browse'));
$router->add('blog.view', '/blog/view/{id}')
->addValues(array('controller' => 'blog.view'));
$dispatcher->setObject('homepage', function ($response) {
return $response->write('<p>Hello conduit! </p><p><a href="/blog">Browse some blog posts</a></p>')->end();
});
$dispatcher->setObject('blog.browse', function ($response) {
return 'Here you can see some blog posts <a href="/blog/view/' . rand(0, 100). ' ">blog post</a>';
});
$dispatcher->setObject('blog.view', function ($response, $id) {
return '<p><a href="/blog">Browse all</a></p><p>I am a blog post ' . htmlspecialchars($id, ENT_QUOTES, 'UTF-8') . '</p>';
});
$server = Server::createServer($app,
$_SERVER,
$_GET,
$_POST,
$_COOKIE,
$_FILES
);
$server->listen();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment