This topic describes the structure and provides examples of event handlers in PHP.

Signatures for event handlers

The following sample code describes the signature for an event handler.

<?php

function handler($event, $context) {
  return 'hello world';
}
Parameter description:
  • handler: the name of the method. The method corresponds to the value that is specified for the Request Handler parameter in the Function Compute console. For example, if the value of the Request Handler parameter for a FC function is index.handler, Function Compute loads the handler function that is defined in index.php and executes the function from the handler function.
  • $event: the parameter that is passed when you invoke the function. The value of this parameter is of the String type. The PHP function directly uses the specified event parameter. You can parse event in the function based on your business requirements. For example, if the input data is a JSON string, you can convert the JSON string to an array.
  • $context: the runtime information of a function, such as the request ID and the temporary identity credentials. You can use the runtime information in your code.

Example 1: Parse JSON-formatted parameters

Sample code

When Function Compute passes the JSON-formatted parameters that you configured, you must parse the parameters in the code. The following sample code provides an example on how to parse an event that is in the JSON format.

<?php

function handler($event, $context) {
  $v = json_decode($event, true);
  var_dump($v['key1']);
  var_dump($v['key2']);
  var_dump($v['key3']);
  return $v;
}

Prerequisites

A function whose runtime environment is PHP is created. For more information, see Create a function.

Procedure

  1. Log on to the Function Compute console.
  2. In the left-side navigation pane, click Services & Functions.
  3. In the top navigation bar, select a region.
  4. Click Functions in the Actions column of the desired service and click the name of the desired function.
  5. On the Function Details page, click the Code tab, enter the preceding sample code in the code editor, and then click Save and Deploy.
    Note In the preceding sample code, the handler is the handler method in index.php. If you specify a different value for the Request Handler parameter, use your actual file and method.
  6. On the Code tab, click the down icon next to Test Function, select Configure Test Parameters from the drop-down list, enter the following test parameters, and then click OK.
    {
      "key1": "value1",
      "key2": "value2",
      "key3": {
        "v1": true,
        "v2": "bye",
        "v3": 1234
      }
    }
  7. Click Test Function.
    After the execution is complete, the response shows that the content in JSON format are returned by the function, and the key1, key2, and key3 content is printed in the log output.

Example 2: Read and write Object Storage Service (OSS) resources by using a temporary AccessKey pair

Sample code

You can use a temporary key pair that is provided by Function Compute to access Object Storage Service (OSS). Example:

<?php

use OSS\OssClient;
use OSS\Core\OssException;

function handler($event, $context) {
    $creds = $context["credentials"];
    $accessKeyId = $creds["accessKeyId"];
    $accessKeySecret = $creds["accessKeySecret"];
    $securityToken = $creds["securityToken"];
    $endpoint = "https://oss-cn-hangzhou-internal.aliyuncs.com";
    $bucket= "randombucket";
    $object = "exampledir/index.php";
    $filePath = "/code/index.php";

    try{
        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false, $securityToken);
        $ossClient->uploadFile($bucket, $object, $filePath);
    } catch(OssException $e) {
        printf(__FUNCTION__ . ": FAILED\n");
        printf($e->getMessage() . "\n");
        return $e->getMessage();
    }
    return 'hello world';
}
Description:
  • $creds = $context["credentials"]: obtains the temporary AccessKey pair from $context. This prevents hard encoding on sensitive information such as passwords.
  • The preceding code indicates that the /code/index.php file is uploaded to the exampledir directory of randombucket in OSS.
    Note Replace endpoint, bucket, object, and filePath with the actual resource names.

Prerequisites

Procedure

  1. Log on to the Function Compute console.
  2. In the left-side navigation pane, click Services & Functions.
  3. In the top navigation bar, select a region.
  4. Click Functions in the Actions column of the desired service and click the name of the desired function.
  5. On the Function Details page, click the Code tab, enter the preceding sample code in the code editor, and then click Save and Deploy.
    Note In the preceding sample code, the handler is the handler method in index.php. If you specify a different value for the Request Handler parameter, use your actual file and method.
  6. Click Test Function.
    After the function is executed, the execution result hello world is returned.

Example 3: Call external commands

You can use a PHP program to create a fork process to call external commands.

If you want to use non-PHP tools, such as shell scripts and executable files compiled in C++ or Go in your PHP functions, you can package and upload the tools and code together, and then run external commands to use these tools. You can use the following methods to run external commands: exec, system, and shell_exec.

The following sample code is used to call the ls -halt command in Linux and generate details of files in the current directory.

<?php

function handler($event, $context) {
  return shell_exec("ls -halt /code");
}