Created
January 21, 2015 14:48
-
-
Save harikt/477902c09eb51dad6433 to your computer and use it in GitHub Desktop.
Conduit router middleware example
This file contains 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 | |
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
Hi Hari,
I currently working on a school project using Aura.Router 3.x.
We're trying to make our project work with Php-pm. Your Middleware approach seem good to me. But you're using an older version of Aura and of Conduit that have been replaced by https://github.com/zendframework/zend-stratigility.
And I can't make it work with newer version :/
Can you give me some hints to make it work for Aura.Router 3.x ?
Thanks