Last active
October 20, 2015 12:36
-
-
Save AndrewCarterUK/970dcba5debbc47772df to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
/** | |
* 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