- Notifications
You must be signed in to change notification settings - Fork37
FaaS (Function as a service) framework for writing portable PHP functions
License
GoogleCloudPlatform/functions-framework-php
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
An open source FaaS (Function as a service) framework for writing portablePHP functions.
The Functions Framework lets you write lightweight functions that run in manydifferent environments, including:
- Your local development machine
- Knative-based environments
The framework allows you to go from:
usePsr\Http\Message\ServerRequestInterface;functionhelloHttp(ServerRequestInterface$request){return"Hello World from a PHP HTTP function!" .PHP_EOL;}
To:
curl http://my-url# Output: "Hello World from a PHP HTTP function!"All without needing to worry about writing an HTTP server or complicated requesthandling logic.
Watchthis video to learn more about Functions Frameworks.
- Spin up a local development server for quick testing
- Invoke a function in response to a request
- Automatically unmarshal events conforming to theCloudEvents spec
- Portable between serverless platforms
Add the Functions Framework to yourcomposer.json file usingComposer.
composer require google/cloud-functions-framework
Create anindex.php file with the following contents:
<?phpusePsr\Http\Message\ServerRequestInterface;functionhelloHttp(ServerRequestInterface$request){return"Hello World from a PHP HTTP function!" .PHP_EOL;}
After completing the steps underInstallation andDefine your Function,run the following commands:
export FUNCTION_TARGET=helloHttpphp -S localhost:8080 vendor/google/cloud-functions-framework/router.phpOpenhttp://localhost:8080/ in your browser and seeHello World from a PHP HTTP function!.
After completing the steps underInstallation andDefine your Function, build the container using the exampleDockerfile:
docker build . \ -f vendor/google/cloud-functions-framework/examples/hello/Dockerfile \ -t my-cloud-functionRun the cloud functions framework container:
docker run -p 8080:8080 \ -e FUNCTION_TARGET=helloHttp \ my-cloud-functionOpenhttp://localhost:8080/ in your browser and seeHello World from a PHPHTTP function. You can also send requests to this function usingcurl fromanother terminal window:
curl localhost:8080# Output: Hello World from a PHP HTTP function!NOTE: For an extensive list of samples, see the [PHP functions samples][functions-samples]and the [official how-to guides][functions-how-to].
Follow theCloud Run function quickstart for PHP to learn how to deploy a function to Cloud Run.
You can manually build your function as a container and deploy it into Cloud Run. Follow theCloud Run instructions for building a function for complete instructions.
The Functions Framework can unmarshall incomingCloudEventspayloads to acloudevent object. This will be passed as arguments to yourfunction when it receives a request. Note that your function must use thecloudevent function signature:
useGoogle\CloudFunctions\CloudEvent;functionhelloCloudEvent(CloudEvent$cloudevent){// Print the whole CloudEvent$stdout =fopen('php://stdout','wb');fwrite($stdout,$cloudevent);}
You will also need to set theFUNCTION_SIGNATURE_TYPE environmentvariable tocloudevent.
export FUNCTION_TARGET=helloCloudEventexport FUNCTION_SIGNATURE_TYPE=cloudeventphp -S localhost:8080 vendor/google/cloud-functions-framework/router.php
In a separate tab, make a cURL request in Cloud Event format to your function:
curl localhost:8080 \ -H "ce-id: 1234567890" \ -H "ce-source: //pubsub.googleapis.com/projects/MY-PROJECT/topics/MY-TOPIC" \ -H "ce-specversion: 1.0" \ -H "ce-type: com.google.cloud.pubsub.topic.publish" \ -d '{"foo": "bar"}'Your original process should output the following:
CLOUDEVENT metadata:- id: 1234567890- source: //pubsub.googleapis.com/projects/MY-PROJECT/topics/MY-TOPIC- specversion: 1.0- type: com.google.cloud.pubsub.topic.publish- datacontenttype:- dataschema:- subject:- time:IMPORTANT: The above tutorials to deploy to a docker container and toCloud Run work for CloudEvents as well, as long asFUNCTION_TARGET andFUNCTION_SIGNATURE_TYPE are set appropriately.
The first parameter of your function is aRequest object which implements thePSR-7ServerRequestInterface:
usePsr\Http\Message\ServerRequestInterface;functionhelloHttp(ServerRequestInterface$request):string{returnsprintf("Hello %s from PHP HTTP function!" .PHP_EOL,$request->getQueryParams()['name'] ??'World');}
You can return a PSR-7 compatibleResponseInterface instead of a string. Thisallows you to set additional request properties such as the HTTP Status Codeand headers.
usePsr\Http\Message\ServerRequestInterface;usePsr\Http\Message\ResponseInterface;useGuzzleHttp\Psr7\Response;useGuzzleHttp\Psr7\Utils;functionhelloHttp(ServerRequestInterface$request):ResponseInterface{$body =sprintf("Hello %s from PHP HTTP function!" .PHP_EOL,$request->getQueryParams()['name'] ??'World');return (newResponse()) ->withBody(Utils::streamFor($body)) ->withStatus(418)// I'm a teapot ->withHeader('Foo','Bar');}
A request to this function will produce a response similar to the following:
HTTP/1.1 418 I'm a teapotHost: localhost:8080Date: Wed, 03 Jun 2020 00:48:38 GMTFoo: BarHello World from PHP HTTP function!See thePSR-7 documentation documentation for more on workingwith the request and response objects.
When you require thegoogle/cloud-storage package with composer, the functionsframework will register thegs:// stream wrapper. This enables your functionto read and write to Google Cloud Storage as you would any filesystem:
// Get the contents of an object in GCS$object =file_get_contents('gs://{YOUR_BUCKET_NAME}/object.txt');// Make modifications$object .="\nadd a line";// Write the new contents back to GCSfile_put_contents('gs://{YOUR_BUCKET_NAME}/object.txt',$object);
You can unregister this at any time by usingstream_wrapper_unregister:
// unregister the automatically registered onestream_wrapper_unregister('gs');
Cloud Run and Cloud Run on GKE both implement theKnative Serving API. The Functions Framework isdesigned to be compatible with Knative environments. Just build and deploy yourcontainer to a Knative environment.
If you want even more control over the environment, you candeploy your container image to Cloud Run on GKE.With Cloud Run on GKE, you can run your function on a GKE cluster, which givesyou additional control over the environment (including use of GPU-basedinstances, longer timeouts and more).
You can configure the Functions Framework using the environment variables shown below:
| Environment variable | Description |
|---|---|
FUNCTION_TARGET | The name of the exported function to be invoked in response to requests. |
FUNCTION_SOURCE | The name of the file containing the source code for your function to load. Default:index.php (if it exists) |
FUNCTION_SIGNATURE_TYPE | The signature used when writing your function. Controls unmarshalling rules and determines which arguments are used to invoke your function. Can be eitherhttp,event, orcloudevent. Default:http |
Contributions to this library are welcome and encouraged. SeeCONTRIBUTING for more information on how to get started.
About
FaaS (Function as a service) framework for writing portable PHP functions
Topics
Resources
License
Contributing
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.