Last active
August 29, 2015 14:17
-
-
Save rdlowrey/27c5f848e2ccaf43b438 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 | |
function myHttpHandler(Request $request, Response $response) { | |
// async function that returns a promise | |
// we use yield to wait for that promise to resolve then resume here | |
// if there's some kind of error it will be thrown into our generator | |
$session = yield loadSessionFromRequest($request); | |
if ($session->hasValue('isLoggedIn')) { | |
// pass the individual promises from generateHttpBody() through using `yield from` | |
// when generateHttpBody() finishes we get its return result in $body | |
$rawHtmlBody = yield from generateHttpBody($request); | |
} else { | |
$response->setStatus(301); | |
$response->setHeader("Location", "http://domain.com/login"); | |
$rawHtmlBody = ''; | |
} | |
$response->send($rawHtmlBody); | |
} | |
function generateHttpBody(Request $request, Session $session) { | |
// returns a promise; pause here until the promise resolves. | |
// this promise is passed through transparently inside myHttpHandler() | |
// because we used `yield from` there. | |
$user = yield loadUserFromDatabase($session->getValue('userId')); | |
// Another promise -- again, this is passed through transparently | |
// because we used `yield from` in myHttpHandler() | |
$template = yield loadTemplateFromRedis($request->getUriPath()); | |
// ... do some stuff here to set template values ... // | |
return $rawHtmlBody; | |
} | |
// And above this layer in the HTTP server code: | |
// $promise = coroutine(myHttpHandler($request, $response)); | |
// $promise->when(...); // we know the response completed here |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment