Serverless PHP

"Serverless" is a bit of a buzzword nowadays. I even went to a conference about it earlier this year.

It is the idea that instead of purchasing a server (or paying a provider for one), you give the provider the functions that you want to run and they will be responsible of putting it on the server and maintaining that side of things.

It is essentially "serverless" to you, the user, as you don't need to worry about any of that kind of stuff. You also only pay when the function is called making a lot cheaper than a dedicated server in certain cases.

My problem so far has been the lack of support for PHP functions. If you know Node or Python, then you have loads of choices to set it up including AWS Lambda.

That was until I went to the above conference and became made aware of Bluemix functions: an IBM implementation of OpenWhisk which is an "open source cloud platform".

For basic executions of up to 5,000,000 executions a month, its free. This experimenting fall well within that price bracket.

Rob Allen did a great blog post to get started using it and that is what I used to get me started to write this one.

Installing the CLI

First thing that you have to do is sign up to IBM Cloud. This the new name for Bluemix, although you will still see the name used for the functions.

Here is the link,

The process is pretty self explanatory. You don't even need payment details. I would advise you put in a name for company even though it is optional as this is used in the URL for your functions later. If you leave it blank it uses the e-mail in the URL which is something you may not want public if you plan on sharing it.

You could create and modify your functions on the web interface but there is a CLI plugin which is probably more preferable as you can then develop on your own setup.

There are instructions for Windows, Mac and Ubuntu. I used Ubuntu so can only speak for that.

First you download the package:

curl -fsSL https://clis.ng.bluemix.net/install/linux | sh

The website then goes through the 4 steps of setting it up which I won't copy and paste here. They even personalise it to pre-fill your e-mail address for settings etc.

The Code

The code for a single function is pretty straightforward. You have a file with a function called "main" which can call other functions or do everything itself.

My example is a simple quadratic equation calculator. It takes 3 parameters a, b and c and does the calculations based on the formula:

So here is the code. I will go through the points of interest for this post below:

function main(array $args) : array
{
    $ouput = [];
    $error = '';
    foreach (['a', 'b', 'c'] as $part) {
        if (isset($args[$part])) {
            if (!is_numeric($args[$part])) {
                $error = $part.' is not a valid integer.'.$args[$part];
                break;
            }
        } else {
            $error = 'Missing value for '.$part.'.';
            break;
        }
    }
    if (!empty($error)) {
        $output['runtime_error'] = $error;
    } else {
        extract($args);
        $value1 = (($b * (-1))+(sqrt((($b**2)-(4*$a*$c)))))/(2*$a);
        $value2 = (($b * (-1))-(sqrt((($b**2)-(4*$a*$c)))))/(2*$a);
        if (is_nan($value1) || is_nan($value2)) {
            $output['runtime_error'] = 'Not a valid quadratic equation.';
        } else {
            $output['x1'] = $value1;
            $output['x2'] = $value2;
        }
    }
    return $output;
}

So the first point of interest is the function signature:

function main(array $args) : array

As you an see, it is called "main" takes a single array called "$args" and has a return type of "array".

$args contains all of the parameters that you call with the function (if any) where the key is the name and value, the value. More later how we pass these but for now accept that they go into the array.

The code itself starts off by validating the input parameters, making sure they are numbers and that none of them are missing. All of the response is going into an array, $output, that is returned at the end.

One thing to note that is that if there is an error, I called the response key "response_error". This is because when it was "error", I got unusual results when running this script on the web.

The returned array is transformed by Bluemix into JSON by default if you do not specify anything.

The rest of the code is doing the calculations. That is not important for this blog so I will leave you to look through that.

Installing and Calling

Once you have done your code, it is time to send it to IBM to host.

To do this, you use a simple command:

bx wsk action update nameOfFunction /path/to/file.php

This will create (or update if it already exists) a function of the said name with the code that you send.

You can see the list of installed actions with:

bx wsk action list

To run a function, in the command line do:

bx wsk action invoke --result nameOfFunction

If you want to add parameters use the param flag:

bx wsk action invoke --result nameOfFunction --param nameOfParam valueOfParam

So with my quadratic equation example, here is me calling with with various parameters to show the error handling.

Note, this is before I changed $output['error'] to $output['runtime_error'], so the response says error. Also note that the response is automatically sent as JSON by default.

If I pass it valid parameters, I get the 2 values of x.

Making it available on Web

Of course one thing you will want to do with these functions is the make them available on the web. This is very easy to do.

When you install the function on IBM, you can add another flag:

bx wsk action update nameOfFunction /path/to/file.php --web true

Now to see the URL, you can do:

bx wsk get nameOfFunction --url

This will give you the full URL of you function. You can then hit this in any web browser and IBM will give you a formatted JSON response. To add parameters, you can do it in the normal way expected on the web: ?param=value&param2=value2. So after doing this with my function, let's see it on the web:

Summary

As you can see, it is incredibly easy to get started with serverless code in PHP. As usual, I have barely scratched the surface with what is possible and I look forward to experimenting in the coming weeks.

No longer do you need to pay for an entire server environment to run a few simple lines of code!

Once again, check out Rob Allen's blog post which helped get me started. He has also done a few more posts delving deeper into what you can do and has a link to a Git repository with more sample code.


© 2012-2017