Skip to content

Instantly share code, notes, and snippets.

@kn0ll
Last active September 26, 2015 07:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kn0ll/1064045 to your computer and use it in GitHub Desktop.
Save kn0ll/1064045 to your computer and use it in GitHub Desktop.
connect-style middleware handling in php.
<?php
namespace satellite;
class Request {
public $method;
public $url;
public $headers;
public function __construct($method, $url, $headers) {
$this->method = $method;
$this->url = $url;
$this->headers = $headers;
}
}
class Response {
public function writeHead($status_code, $headers) {
}
public function write($chunk) {
}
public function end($data) {
}
}
class Middleware {
public $request;
public $response;
public $chain = array();
public function __construct() {
$this->request = new Request(
$_SERVER['REQUEST_METHOD'],
$_SERVER['REQUEST_URI'],
$this->get_headers());
$this->response = new Response();
$this->chain = func_get_args();
}
public function add($middleware) {
array_push($this->chain, $middleware);
}
public function run($i = 0) {
$self = $this;
if ($m = $this->chain[$i]) {
$middleware = new $m();
$middleware($this->request, $this->response, function() use ($self, $i) {
$self->run($i + 1);
});
}
}
private function get_headers() {
if(function_exists('apache_request_headers')) {
return apache_request_headers();
}
// http://www.electrictoolbox.com/php-get-headers-sent-from-browser/
$headers = array();
foreach($_SERVER as $key => $val) {
if(substr($key, 0, 5) == 'HTTP_') {
$headers[str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))))] = $val;
}
}
return $headers;
}
}
<?php
require "satellite.php";
class Love {
public function __invoke($req, $res, $next) {
echo 'I love ';
$next();
}
}
class Lamb {
public function __invoke($req, $res, $next) {
echo 'my lambs';
$next();
}
}
// will print "I love my lambs"
$m = new satellite\Middleware(Love, Lamb);
$m->run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment