Skip to content

Instantly share code, notes, and snippets.

@AndrewCarterUK
Last active October 20, 2015 12:36
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 AndrewCarterUK/970dcba5debbc47772df to your computer and use it in GitHub Desktop.
Save AndrewCarterUK/970dcba5debbc47772df to your computer and use it in GitHub Desktop.
<?php
/**
* What an async proxy server might look like in PHP with a PSR for event loops
*/
use EventLoopImplementation\EventLoop;
use HttpClientImplementation\HttpClient;
use HttpServerImplementation\HttpServer;
use PromiseImplementation\Promise;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
/**
* The HttpServer and HttpClient both depend on the EventLoop. They will add their non-blocking read
* and write streams to this event loop.
*/
$loop = new EventLoop;
$server = new HttpServer('localhost:8000', $loop);
$client = new HttpClient($loop);
$proxyDomain = 'http://domain-to-proxy.com/';
$server->on('request', function (ServerRequestInterface $request) use ($client, $proxyDomain) {
$responsePromise = new Promise;
/**
* HttpClient::get() immediately returns a promise which will later be fulfilled with a PSR-7
* response from the server or an error.
*/
$client
->get($proxyDomain . $request->getRequestTarget())
->then(
function (ResponseInterface $response) use ($responsePromise) {
$responsePromise->resolve($response);
},
function ($error) {
$responsePromise->reject($error);
}
);
return $responsePromise;
});
$loop->run();
/**
* This is the same as the code below, but real world use cases are unlikely to be this simple.
*/
$server->on('request', function (ServerRequestInterface $request) use ($client, $proxyDomain) {
return $client->get($proxyDomain . $request->getRequestTarget());
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment