0% found this document useful (0 votes)
54 views

Serverless, Reactphp, and Expanding Frontiers

This document summarizes an article about deploying PHP applications on AWS Lambda using the Bref serverless framework. It begins by introducing serverless computing and its advantages over traditional hosting. The article then provides steps to set up an AWS account and configure credentials for the Bref CLI tool using IAM policies. Specifically, it describes creating a new IAM user called "bref-agent" with programmatic access and attaching a policy that grants permissions for serverless resources like S3, DynamoDB, CloudFormation, Lambda and more. This sets the stage to deploy a "Hello World" PHP Lambda function in the next part.

Uploaded by

Leonel rugama
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views

Serverless, Reactphp, and Expanding Frontiers

This document summarizes an article about deploying PHP applications on AWS Lambda using the Bref serverless framework. It begins by introducing serverless computing and its advantages over traditional hosting. The article then provides steps to set up an AWS account and configure credentials for the Bref CLI tool using IAM policies. Specifically, it describes creating a new IAM user called "bref-agent" with programmatic access and attaching a policy that grants permissions for serverless resources like S3, DynamoDB, CloudFormation, Lambda and more. This sets the stage to deploy a "Hello World" PHP Lambda function in the next part.

Uploaded by

Leonel rugama
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

www.phparch.

com May 2019


Volume 18 - Issue 5

Serverless, ReactPHP,
and Expanding Frontiers

Deploying ReactPHP Applications


Serverless PHP With Bref, Part One
MySQL 8.0 Geographic Information
System or How Did I Get to This Point?
Department of Breaking Changes:
Launching PHP 7 in a Highly Available Web World

ALSO INSIDE
Education Station: Internal Apparatus: finally{}:
Data Structures, Part One Memory Abstractions The State of PHP
Community Corner: Security Corner:
Philosophy and Burnout, Access Control and
Part One Authorization
DaTA
M ay 3 1 s t • ONLINE

Data is more valuable than oil.


Data is the lifeblood of more and more companies every day.
In every enterprise, data comes from multiple inputs and must be harnessed and combined
to become actionable. If you don’t tame and act on your data streams, you lose value as it
flows through your systems and you miss opportunities. The decisions for dealing with your
data go beyond how you store, search, and share it with others throughout your
organization.

Join us online for the next Day Camp 4 Developers and learn to tame your data. Turn it from
a wandering stream to a powerful tool that can inform your enterprise.

May 31, 2019 | 9:00 AM - 3:00 PM CDT | Online

daycamp4developers.com

Tickets include attendance to the live event as well as access to download the videos within seven days after the event.
FEATURE

Serverless PHP With Bref, Part One


Rob Allen
In recent years, a different way to build applications has arisen called serverless
computing. This term is not a good name; I’m reminded of the adage that there
are two hard problems in programming: naming things, cache invalidation, and
off-by-one errors. Serverless computing as a name implies no servers, but there
are servers—you don’t think about them though. A better way to think about it is
that the servers and the management of them are abstracted away and the provider
manages the allocation of resources, not the application architect.
Amazon Lambda1 arguably started functionality required to deploy PHP Now we have the tools we need to set
Serverless computing. It is a system functions into Lambda in a simple, clean up credentials so SAM can create and
where your code runs on demand and is and easy manner. It provides runtimes manage the application resources for us.
not even in memory if it’s not running. for PHP 7.2 and 7.3. It is closely tied If you don’t have an AWS account, head
We call this functions as a service (FaaS). to Amazon, so if you’re interested in to https://console.aws.amazon.com and
Modular code executes in response to running PHP in say IBM Cloud Func- create one. The command line tools
an event, and so different parts of our tions, you would use a different tool, require access keys. To do this, we need
application can be scaled independently such as Serverless Framework3. a new user as we don’t want to use our
without any additional effort on our Let’s get started by setting up AWS. master user. This process is well-de-
part. The main advantages are that we scribed in the Serverless Framework
spend more our time concentrating on Setting Up AWS documentation6.
the core of an application that brings In summary:
Let’s start by creating a single Lambda
value and far less worrying about how 1. Create or log into your AWS
Hello World application. First, we have
to run and scale it. There’s also a lovely account and go to the Identity and
to start with our prerequisites: the
side-benefit in that you only pay when Access Management (IAM) page.
AWS command line tools and an AWS
your code is running, so your costs are
account. This involves more steps than 2. Click on Users then Add User and
proportional to usage. As FaaS encour-
you would initially think because AWS enter the username bref-agent.
ages building small independent units
has a robust and complete permissions 3. For the Access type, select Program-
of functionality, you also get modular
system called IAM4 that controls user matic access only as this user needs
applications.
access, so in addition to installing the CLI and API access, but not web
Of course, there were also disadvan- command line tools, we also need to set console access.
tages. It is harder to reason about an up a user with enough permissions to
application which is spread over many 4. Click Next: Permissions to set
create our application.
separate functions and services. It’s permissions for our user.
There are two command line tools
also harder to debug and keep track of 5. Click Attach existing policies
we need: aws and sam. As you can guess,
which functions are deployed where. directly and then Create Policy.
from its name, aws is the command
FaaS and serverless are not a solution to 6. In the new tab that opens, click
line tool which allows access to all
every problem but are a good solution JSON and paste in the JSON from
of the AWS system. The other tool,
for a large number of use-cases. Listing 1.
sam is the way we interact with AWS
In this article, I’m going to walk Serverless Application Model (SAM) 7. Click Review Policy and assign it a
through how to use Lambda with PHP system which is used by Bref. To install name of “bref-agent-policy,” then
to execute a function. In part two, I will the aws command line tool, head to click Create Policy, and close the
build a static website hosted on S3, with https://aws.amazon.com/cli/ and follow tab to return to the tab where we
a CDN updated via a Lambda function. the instructions5; for sam. are adding our user.
To do this, we use Bref2. Created by 8. Click the refresh button (two
Matthieu Napoli, Bref contains all the 3 Serverless Framework: arrows in a circle) on the right to
https://serverless.com
refresh the list of available policies
1 Amazon Lambda: 4 IAM: https://aws.amazon.com/iam/
https://aws.amazon.com/lambda/ 5 the instructions: 6 Serverless Framework documentation:
2 Bref: https://bref.sh https://phpa.me/aws-serverless-sam https://phpa.me/aws-serverless-credentials

10 \ May 2019 \ www.phparch.com


Serverless PHP With Bref, Part One

9. Find bref-agent-policy in the list, check the box next to it,


Listing 1
and click Next: Tags.
10. We don’t want to add any tags, so click Next: Review, and 1. {
then Create user. 2. "Statement": [
Listing 1 is the set of permissions we give to the user that 3. {
4. "Action": [
creates our serverless application, so it has administrative
5. "apigateway:*",
permissions to create S3 buckets, DynamoDB tables, Cloud- 6. "cloudformation:*",
Formation stacks, IAM policies, and so on. It is a fairly open 7. "dynamodb:*",
policy so for production use; you may want to lock it down 8. "events:*",
some more with specific permissions for each group. 9. "iam:*",
We now have a new user called bref-agent. Note the Access 10. "lambda:*",
key ID and the Secret access key. 11. "logs:*",
12. "s3:*",
Configure the AWS CLI 13. "sns:*",
14. "states:*"
The easiest way to configure the aws and sam tools is to run 15. ],
aws configure. 16. "Effect": "Allow",
17. "Resource": "*"
$ aws configure 18. }
AWS Access Key ID [None]: AKIAIOSFODNN7EXAMPLE 19. ],
AWS Secret Access Key [None]: wJalrXUtnFEMI/K7MDENG/EXAMPLEKEY 20. "Version": "2012-10-17"
Default region name [None]: us-east-1
21. }
Default output format [None]: json

Use your Access key ID and the Secret access key at the Output 1
prompts, set your region to us-east-1, and use JSON for your
output format. 1. $ vendor/bin/bref inito
2.
Now that we have AWS set up, we can write our first 3. What kind of lambda do you want to create? (You will be
Lambda function. 4. able to add more functions later by editing
5. `template.yaml`) [PHP function]:
Hello World With Bref 6. [0] PHP function
7. [1] HTTP application
To create a Lambda function using Bref, we start with a new
8. [2] Console application
directory and install Bref into it: 9. > 0
10.
$ mkdir bref-hello-world 11. Creating template.yaml
$ cd bref-hello-world
12. Creating index.php
$ composer require mnapoli/bref
13.
14.
These commands installed the Bref code into the vendor/ 15. [OK] Project initialized and ready to test or deploy.
folder, so we can go ahead a create the project now. You’ll see
something like Output 1
Listing 2
Bref supports three different kinds of serverless projects
depending on your needs. For our case, we want a standard 1. AWSTemplateFormatVersion: '2010-09-09'
Lambda function, so we select the [0] PHP function option, 2. Transform: AWS::Serverless-2016-10-31
and then Bref creates our files. To learn more about the 3. Description: ''
options, see the Bref documentation on runtimes7 4.
5. Resources:
What Files Do We Have? 6. MyFunction:
7. Type: AWS::Serverless::Function
bref init has created two files of interest: template.yaml 8. Properties:
and index.php. Starting with template.yaml, we have the SAM 9. FunctionName: 'my-function'
template which is the configuration file which defines our 10. Description: ''
application and in our case contains the definition of our first 11. CodeUri: .
12. Handler: index.php
Lambda function (see Listing 2). 13. Timeout: 10 # Timeout in seconds
14. MemorySize: 1024 # Relates to pricing and CPU power
15. Runtime: provided
16. Layers:
17. - 'arn:aws:lambda:us-east-1:209497400698:layer:php-73:1'
7 runtimes: https://bref.sh/docs/runtimes/

www.phparch.com \ May 2019 \ 11


Serverless PHP With Bref, Part One

The template file consists of a small header and the Resources Deployment is done using the sam tool; however, first, we
section which holds our function. Its resource name isMyFunc- need to create an S3 bucket to store the CloudFormation
tion and it has a type of AWS::Serverless::Function. To define stack in.
our function’s properties, we provide a set of configuration
information under the Properties key. The table below shows $ aws s3 mb s3://helloworld-rka-brefapp
the key properties for a Lambda function.
You can name your bucket anything you like, but it must
be globally unique. I like to postfix with my initials and the
Property name Value Notes reason for the bucket to ensure it’s unique and that I can
The name of the Lambda
remember what it’s for.
function. Note that this is There are two steps to deploying our application. First, we
FunctionName my-function not the same same name upload the code and generate a CloudFormation stack into
as the CloudFormation our S3 bucket and then we deploy the stack:
resource name (MyFunction).
CodeUri . The path to the source code. $ sam package --output-template-file .stack.yaml \
--s3-bucket helloworld-rka-brefapp
The PHP file containing the $ sam deploy --template-file .stack.yaml \
Handler index.php lambda function the Bref --capabilities CAPABILITY_IAM \
runtime layer will invoke. --stack-name helloworld-rka-brefapp
$ rm .stack.yaml
The language runtime that
will invoke the function. For The output template file (.stack.yaml) is an intermediate
Runtime provided Bref, this isprovidedas we
CloudFormation file and isn’t needed after deploy. The stack
provide the runtime layer to
Lambda.
name must be unique within the AWS region, so I name it the
same as my S3 bucket.
By default this is Bref ’s PHP
7.3 runtime layer from the Running Our Function
us-east-1 region. See this list
Layers A List of layers To invoke our function, we can use bref.
https://runtimes.bref.sh for
the correct ARNs for other
$ vendor/bin/bref invoke my-function
regions and PHP versions. START RequestId: 4fa0f083-c02f-4b35-a23f-1e5e35d91af5
Version: $LATEST
As you can see, our template defines a single resource: a END RequestId: 4fa0f083-c02f-4b35-a23f-1e5e35d91af5
Lambda function called my-function that lives in index.php REPORT RequestId: 4fa0f083-c02f-4b35-a23f-1e5e35d91af5
within the current directory. Let’s take a look at index.php: Duration: 24.15 ms Billed Duration: 100 ms
Memory Size: 1024 MB Max Memory Used: 68 MB
<?php declare(strict_types=1);
"Hello world"
require __DIR__ . '/vendor/autoload.php';
To send data to our function we can pass in a JSON object
lambda(function (array $event) {
return 'Hello ' . ($event['name'] ?? 'world'); to the--eventparameter like this:
});
$ vendor/bin/bref invoke my-function \
A Bref Lambda function is defined as a closure that’s an --event '{"name": "Rob"}'
argument to Bref ’s lambda() function. It takes an array $event
Which results in the output of Hello Rob.
which contains the input data to the function, and you can
return whatever you want as long as it’s JSON serializable. Tidying Up
This $event contains information about the request which We can delete the application using:
triggered your lambda function8. In this case, we return the
string Hello followed by the name if it exists, otherwise world. aws cloudformation delete-stack \
--stack-name helloworld-rka-brefapp
Deploying Our Function
If you used the us-east-1 region for your configuration as We also need to delete the S3 bucket with:
recommended, then we can go ahead and deploy our func-
aws s3 rb s3://helloworld-rka-brefapp
tion immediately.

8 lambda function: https://phpa.me/aws-lambda-other

12 \ May 2019 \ www.phparch.com


Serverless PHP With Bref, Part One

Other Ways to Invoke Our Listing 4


Function
Invoking a function with the 1. Resources:
command line or an authenticated 2. MyFunction:
3. Type: AWS::Serverless::Function
AWS API call is not the easiest way to
4. Properties:
execute our code; usually, you want 5. FunctionName: 'my-function'
it to respond to an event of some 6. # ...
sort. Lambda supports many different 7. Events:
event sources, such as a queue, data- 8. MySchedule:
base change, S3 bucket change, HTTP 9. Type: Schedule
request or a cron-type schedule. For 10. Properties:
your function to respond to an event, 11. Schedule: rate(1 minute)
you need to update the template defini-
tion with the event you want to respond $ sam logs --name my-function --tail of all, we only pay when our code runs.
to. The list of event source types can be There are many situations where this
found in the SAM documentation9. Don’t forget to remove the paradigm can be used to add function-
To schedule our function at regular MySchedule event and redeploy to turn ality to an existing application or to
intervals, we add a Schedule event to our it off again. write a brand new application such as
function in template.yaml like Listing 4. an API.
We add a new property called events
Conclusion As serverless applications tend to
and can then add as many event sources I’ve given you a taste for writing utilize other services, in part two of this
as we want. In this case, we create one serverless functions with PHP. It is a series, I look at how we can write a real
event source, MySchedule which has powerful paradigm, and with Bref, we application which integrates a Lambda
a rate of one minute. The schedule can use our PHP easily on AWS Lambda. function with AWS S3 cloud storage
property may be either a cron or a rate As PHP developers, we too can benefit and the CloudFront CDN in order
expression as explained in Schedule from this environment where our code create a static website updated with new
Expressions for Rules10 in the Cloud- executes in response to an event, auto- images from Flickr.
Watch documentation. matically scaled as required and best
We run the sam package and sam
deploy commands again to deploy the Rob Allen is a software consultant and developer with
change to Lambda and now our func- many years experience and writes code in PHP, Python, Swift
tion is executing once every minute. and other interesting languages. He’s led Slim Framework’s
development team and contributes to rst2pdf, Apache Open-
To prove our function is executing
Whisk and other open source projects. Rob is a published
once per minute, we can look in the
author and based in the UK where he runs Nineteen Feet
CloudWatch logs. You can do this via
Limited11, focusing on API development, training and consul-
the AWS console on the web or via
tancy. In his spare time, Rob blogs at akrabat.com12 and can
the command line using the following
often be seen with a camera in his hand. @akrabat
command to see the Lambda function
execution happening every minute.

Related Reading
9 SAM documentation:
https://phpa.me/sam-event-types • Moving a Monolith to AWS by Keanan Koppenhaver. May 2018.
10 Schedule Expressions for Rules: https://phparch.com/article/moving-a-monolith-to-aws/
https://phpa.me/cloudwatch-events-rules • Community Corner: What’s the Fuss About Serverless?
11 Nineteen Feet Limited: http://19ft.com by James Titcumb. April 2018.
12 akrabat.com: https://akrabat.com https://phpa.me/april-2018-serverless

www.phparch.com \ May 2019 \ 13

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy