Introduction to Serverless Computing
Serverless computing is a cloud-computing execution model where the cloud provider dynamically manages the allocation and provisioning of servers. In this model, the term “serverless” is a bit of a misnomer, as servers are still used, but developers are abstracted from the details of server management. Instead of worrying about infrastructure, developers can focus solely on writing code.
Serverless computing provides several benefits:
Cost Efficiency: You only pay for the compute time you use.
Scalability: Automatically scales with the number of requests.
Simplified Backend Management: No need to maintain or scale servers manually.
Popular serverless platforms include AWS Lambda, Azure Functions, Google Cloud Functions, and others. These platforms support various programming languages, including PHP, either directly or through custom runtimes.
Building Serverless Applications with PHP
Although PHP is not natively supported by all serverless platforms, it can still be used effectively in a serverless environment through custom runtimes or containers. In this article, we’ll explore how to build serverless PHP applications using AWS Lambda, one of the most popular serverless platforms.
Step 1: Setting Up Your Development Environment
Before we start, ensure you have the following installed on your system:
PHP
Composer
AWS CLI
Docker
Additionally, you’ll need an AWS account to deploy your serverless application.
Step 2: Writing the PHP Lambda Function
AWS Lambda functions are essentially scripts that AWS runs in response to events. For our PHP Lambda function, we’ll write a simple PHP script that handles HTTP requests.
Create a directory for your project and navigate into it:
mkdir serverless-php
cd serverless-php
Create a lambda.php file with the following content:
200,
'body' => json_encode(['message' => "Hello, $name!"]),
'headers' => [
'Content-Type' => 'application/json'
]
];
return $response;
}
This simple Lambda function reads a name from the request body and returns a greeting.
Step 3: Creating a Custom Runtime
Since AWS Lambda does not natively support PHP, we need to create a custom runtime using Docker. Create a Dockerfile in your project directory:
FROM amazonlinux:2
# Install dependencies
RUN yum -y install \
php \
php-json \
php-mbstring \
php-xml \
php-zip \
unzip \
curl \
zip
# Install the Lambda runtime interface client
RUN curl -o /tmp/aws-lambda-runtime-interface-emulator.zip https://github.com/aws/aws-lambda-runtime-interface-emulator/releases/latest/download/aws-lambda-runtime-interface-emulator.zip && \
unzip -d /usr/local/bin/ /tmp/aws-lambda-runtime-interface-emulator.zip
# Copy application files
COPY lambda.php /var/task/
# Set the entrypoint to the Lambda runtime interface emulator
ENTRYPOINT ["/usr/local/bin/aws-lambda-rie", "php", "lambda.php"]
This Dockerfile creates an environment for running PHP in AWS Lambda by installing PHP and the AWS Lambda runtime interface emulator.
Step 4: Building and Testing the Docker Image
Build the Docker image:
docker build -t php-lambda .
To test the Lambda function locally, you can use the AWS Lambda runtime interface emulator. Start the emulator with the following command:
docker run -p 9000:8080 php-lambda
Send a test request to the emulator:
curl -XPOST "http://localhost:9000/2015-03-31/functions/function/invocations" -d '{"body": "{\"name\": \"John\"}"}'
You should receive a response:
{"statusCode":200,"body":"{\"message\":\"Hello, John!\"}","headers":{"Content-Type":"application/json"}}
Step 5: Deploying to AWS Lambda
Now that we have our Lambda function and custom runtime, we can deploy it to AWS Lambda using the AWS CLI.
Step 5.1: Create a ZIP Package
First, create a ZIP package containing your lambda.php file:
zip function.zip lambda.php
Step 5.2: Create an S3 Bucket
Create an S3 bucket to upload your ZIP package (if you don’t already have one):
aws s3 mb s3://your-bucket-name
Upload the ZIP package to S3:
aws s3 cp function.zip s3://your-bucket-name/function.zip
Step 5.3: Create a Lambda Function
Create a new Lambda function using the AWS CLI:
aws lambda create-function --function-name php-lambda \
--runtime provided.al2 \
--role arn:aws:iam::your-account-id:role/your-lambda-execution-role \
--handler lambda.handler \
--code S3Bucket=your-bucket-name,S3Key=function.zip \
--package-type Zip \
--environment Variables={AWS_LAMBDA_EXEC_WRAPPER=/usr/local/bin/aws-lambda-rie}
Replace your-account-id and your-lambda-execution-role with your AWS account ID and the ARN of an IAM role that AWS Lambda can assume to execute the function.
Step 5.4: Create an API Gateway
To make your Lambda function accessible via HTTP, create an API Gateway:
aws apigatewayv2 create-api --name "PHP API" --protocol-type HTTP
Create an integration for the API:
aws apigatewayv2 create-integration --api-id your-api-id \
--integration-type AWS_PROXY \
--integration-uri arn:aws:apigateway:your-region:lambda:path/2015-03-31/functions/arn:aws:lambda:your-region:your-account-id:function:php-lambda/invocations
Replace your-api-id, your-region, and your-account-id with your API ID, AWS region, and AWS account ID.
Create a route for the API:
aws apigatewayv2 create-route --api-id your-api-id --route-key "POST /invoke" --target integrations/your-integration-id
Deploy the API:
aws apigatewayv2 create-deployment --api-id your-api-id --stage-name prod
Step 6: Testing the Deployed Lambda Function
After deploying the API, you can invoke your Lambda function via HTTP. Use the following command to send a test request:
curl -XPOST "https://your-api-id.execute-api.your-region.amazonaws.com/prod/invoke" -d '{"body": "{\"name\": \"John\"}"}'
You should receive a response similar to the one you received when testing locally:
{"statusCode":200,"body":"{\"message\":\"Hello, John!\"}","headers":{"Content-Type":"application/json"}}
Conclusion
Serverless computing offers a powerful way to build and deploy applications without the need for managing servers. By leveraging AWS Lambda and custom runtimes, you can run PHP applications in a serverless environment. This article walked you through creating a simple serverless PHP application, deploying it to AWS Lambda, and making it accessible via API Gateway.
Serverless architecture simplifies deployment, enhances scalability, and reduces operational overhead, making it an excellent choice for modern application development. With these tools and techniques, you can harness the benefits of serverless computing to build efficient and cost-effective PHP applications.