Developing software in the Real World

Using Composer packages with OpenWhisk

When creating new OpenWhisk actions in PHP, It’s likely that you’ll want to take advantage of the rich ecosystem of Composer packages on Packagist.org.

The OpenWhisk PHP runtime has you covered with some pre-installed Composer packages and also the ability to upload your own using a zip file.

Pre-installed Composer packages

The PHP runtime ships with two Composer packages by default: Guzzle and ramsey/uuid.

This is handy as if you need to make an API call from your action, then you have the full power to Guzzle at your fingertips. The ramsey/uuid library is also handy for those times when you need a UUID when PUT’ing to that API.

If you need anything else then you have to do a bit more leg work.

Uploading your own project files

The PHP runtime also accepts a zip file when creating or updating an action. This means that you can create a PHP project for your action that includes a composer.json.

For example, let’s say that you want to use NFNumberToWord in your action.

Create the PHP project

Firstly, create the composer.json file:

This creates composer.json, composer.lock and a vendor directory with the component and autoloader code in it.

We now need an action file. This must be called index.php:

index.php:

The main function takes an associative array of arguments and must return an associative array which is converted to JSON for us. As with any other library, we import it using a use statement and can then instantiate the class and call toWords() on it.

Note that we don’t need to include the Composer autoload file as this is done automatically by the PHP runtime.

Upload to OpenWhisk

To upload to OpenWhisk we first zip up the files and then use the wsk command line client to create the action:

The name of the zip file is immaterial, so I’ve used something simple. Now we upload it to OpenWhisk:

In this case, I’ve named the action n2w and passed in the zip file we have just created and specified the runtime to use with the --kind parameter. This is needed because we are supplying a zip file as our action code and OpenWhisk need to know which runtime to use for it.

That’s it. We’re done.

Running our action

We can prove it worked using:

This outputs:

Fin

As you can see, it’s really easy to take advantage of the vast library of Packagist components in your actions, but of course, if all you need is an HTTP client, then Guzzle is already available.

One thought on “Using Composer packages with OpenWhisk

Thoughts? Leave a reply

Your email address will not be published. Required fields are marked *