Event handlers

更新时间:
复制 MD 格式

In the PHP runtime, an event handler is a PHP function that Function Compute invokes when a trigger fires. This page covers the handler signature, parameter details, and working code examples.

On this page:

Handler signature

<?php

function handler($event, $context) {
  return 'hello world';
}
ParameterTypeDescription
handlerMethod nameMaps to the Request Handler value in the Function Compute console. For example, index.handler tells Function Compute to load index.php and call the handler function.
$eventStringThe raw input passed when the function is invoked. The PHP runtime delivers this as a string — the runtime does not convert the payload automatically. Parse it in your handler as needed (for example, use json_decode to convert a JSON payload to an array).
$contextArrayRuntime metadata for the invocation, including the request ID and temporary identity credentials. Access credentials via $context["credentials"] to authenticate calls to other Alibaba Cloud services.

Parse JSON parameters

When the input event is a JSON string, use json_decode to convert it to a PHP array before accessing individual fields.

<?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

Before you begin, ensure that you have:

  • A Function Compute function with the PHP runtime

Test the handler

  1. Log on to the Function Compute console. In the left-side navigation pane, click Services & Functions.

  2. In the top navigation bar, select a region. On the Services page, click the target service.

  3. On the Functions page, click the function name.

  4. On the Function Details page, click the Code tab, paste the sample code into the code editor, and then click Deploy.

    The sample code assumes the handler is the handler method in index.php. If your Request Handler value differs, update the file name and method name accordingly.
  5. Click the dropdown arrow next to Test Function, select Configure Test Parameters, enter the following test event, and then click OK.

    {
      "key1": "value1",
      "key2": "value2",
      "key3": {
        "v1": true,
        "v2": "bye",
        "v3": 1234
      }
    }
  6. Click Test Function.

After execution, the response contains the JSON-formatted return value, and the log output prints the values of key1, key2, and key3.

Read and write OSS objects using temporary credentials

Function Compute provides temporary identity credentials through $context. Use these credentials to access Object Storage Service (OSS) without hard-coding an AccessKey ID or AccessKey secret in your code.

<?php

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

function handler($event, $context) {
    // Retrieve temporary credentials from the context object.
    // Do not hard-code AccessKey IDs or secrets — this approach
    // keeps credentials out of your source code and avoids leaking
    // access to all resources under your account.
    $creds = $context["credentials"];
    $accessKeyId     = $creds["accessKeyId"];
    $accessKeySecret = $creds["accessKeySecret"];
    $securityToken   = $creds["securityToken"];

    // Replace the following values with your actual OSS resource names.
    $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';
}

The code above uploads /code/index.php to the exampledir/ directory in the randombucket OSS bucket. Replace endpoint, bucket, object, and filePath with your actual values.

Prerequisites

Before you begin, ensure that you have:

Deploy and test

  1. Log on to the Function Compute console. In the left-side navigation pane, click Services & Functions.

  2. In the top navigation bar, select a region. On the Services page, click the target service.

  3. On the Functions page, click the function name.

  4. On the Function Details page, click the Code tab, paste the sample code into the code editor, and then click Deploy.

    The sample code assumes the handler is the handler method in index.php. If your Request Handler value differs, update the file name and method name accordingly.
  5. Click Test Function.

After execution, the function returns hello world.

Call external commands

PHP can spawn a child process to run external commands using exec, system, or shell_exec. This lets you package non-PHP tools — such as shell scripts or binaries compiled in C++ or Go — alongside your PHP code and invoke them at runtime.

The following example runs ls -halt on the /code directory and returns the file listing.

<?php

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