Skip to content

Instantly share code, notes, and snippets.

@mindplay-dk
Last active August 29, 2015 14:15
Show Gist options
  • Save mindplay-dk/11e7c08ff6aa4d3486a4 to your computer and use it in GitHub Desktop.
Save mindplay-dk/11e7c08ff6aa4d3486a4 to your computer and use it in GitHub Desktop.
Example middleware using Walkway as a router with Conduit
<?php
use mindplay\walkway\Route;
use Phly\Conduit\MiddlewareInterface;
use Phly\Conduit\MiddlewarePipe;
use Phly\Http\Server;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
require __DIR__ . '/vendor/autoload.php';
// Simple middle-ware layer for Walkway Modules:
class WalkwayMiddleware implements MiddlewareInterface
{
/**
* @var mindplay\walkway\Module
*/
private $router;
public function __construct(mindplay\walkway\Module $router)
{
$this->router = $router;
}
/**
* {@inheritdoc}
*/
public function __invoke(Request $request, Response $response, callable $next = null)
{
$path = $request->getUri()->getPath();
$method = $request->getMethod();
$this->router->vars['request'] = $request;
$this->router->vars['response'] = $response;
$route = $this->router->resolve($path);
if ($route === null) {
return $next($request, $response);
}
$result = $route->execute($method);
if ($result instanceof Response) {
$response = $result;
} else {
$response->getBody()->write($result);
}
return $response;
}
}
// Sample Walkway Module:
$router = new mindplay\walkway\Module();
$router['hello'] = function (Route $route) {
$route['world'] = function (Route $route) {
$route->get = function(Request $request) {
return '<h1>Hello, World!</h1><pre>' . htmlspecialchars(print_r($request, true)) . '</pre>';
};
};
};
// Configure and run Conduit:
$app = new MiddlewarePipe();
$app->pipe(new WalkwayMiddleware($router));
$server = Server::createServer($app, $_SERVER, $_GET, $_POST, $_COOKIE, $_FILES);
$server->listen();
@mindplay-dk
Copy link
Author

The above example is a basic Conduit middleware adapter and front-controller for the Walkway router library.

This is based on the proposed PSR-7 standard and package.

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