Last active
March 28, 2019 16:48
-
-
Save okelet/afe16efea9b89ce90e4690dd752cb4ae to your computer and use it in GitHub Desktop.
This file contains 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
#!/opt/bin/php -d memory_limit=-1 | |
<?php | |
// Adapted from https://aws.amazon.com/es/blogs/apn/aws-lambda-custom-runtime-for-php-a-practical-example/ | |
// This invokes Composer's autoloader so that we'll be able to use Guzzle and any other 3rd party libraries we need. | |
require __DIR__ . '/vendor/autoload.php'; | |
function getNextRequest() | |
{ | |
$client = new \GuzzleHttp\Client(); | |
$response = $client->get('http://' . $_ENV['AWS_LAMBDA_RUNTIME_API'] . '/2018-06-01/runtime/invocation/next'); | |
return [ | |
'invocationId' => $response->getHeader('Lambda-Runtime-Aws-Request-Id')[0], | |
'payload' => json_decode((string) $response->getBody(), true) | |
]; | |
} | |
function sendResponse($invocationId, $response) | |
{ | |
$client = new \GuzzleHttp\Client(); | |
$client->post( | |
'http://' . $_ENV['AWS_LAMBDA_RUNTIME_API'] . '/2018-06-01/runtime/invocation/' . $invocationId . '/response', | |
['body' => $response] | |
); | |
} | |
// This is the request processing loop. Barring unrecoverable failure, this loop runs until the environment shuts down. | |
do { | |
// Ask the runtime API for a request to handle. | |
$request = getNextRequest(); | |
// Obtain the function name from the _HANDLER environment variable and ensure the function's code is available. | |
$handler = $_ENV['_HANDLER']; | |
$namespace = explode('::', $handler)[0]; | |
$namespaceAppSrc = preg_replace("/^App\\\/", "src\\", $namespace); | |
$namespacePath = explode('\\', $namespaceAppSrc); | |
require_once($_ENV['LAMBDA_TASK_ROOT'] . "/" . implode("/", $namespacePath) . ".php"); | |
// Execute the desired function and obtain the response. | |
$response = call_user_func($_ENV['_HANDLER'], $request['payload']); | |
// Submit the response back to the runtime API. | |
sendResponse($request['invocationId'], $response); | |
} while (true); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment