All Products
Search
Document Center

Function Compute:Handlers

Last Updated:Jul 24, 2024

You can use PHP handlers to respond to received events and execute corresponding business logic. This topic describes concepts and structure of PHP handlers and provides examples.

What is a handler?

A handler for a function in Function Compute is the method to process requests in function code. When the function is invoked, Function Compute uses the handler that you configure to process requests. You can configure a handler for a function by specifying the Handler parameter in the Function Compute console.

Handlers of PHP functions in Function Compute follow the File name.Method name format. For example, if your file name is main.php and your method name is handler, the handler is main.handler.

For more information about functions in Function Compute and related operations, see Create an event function.

Configurations of handlers must conform to the configuration specifications of Function Compute. The configuration specifications vary based on the handler type.

Signatures for handlers

The following sample code shows a simple signature for a handler:

<?php

function handler($event, $context) {
  return 'hello world';
}

Parameter description:

  • handler: the name of the method to process requests. 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 Handler parameter for a Function Compute function is index.handler, Function Compute loads the handler method that is defined in index.php and executes the function from handler.

  • $event: the parameter that is passed when you invoke the function. The value of this parameter is a string. 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 context information, such as the request ID and the temporary credentials. The information can be used in your code.

Note

If you want to use HTTP triggers or custom domain names to access functions, obtain request struct before you define HTTP responses. For more information, see Use an HTTP trigger to invoke a function.

Example 1: Parse JSON-formatted parameters

Sample code

When you pass JSON-formatted parameters into functions of Function Compute, Function Compute passes through the parameters, and you need to 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;
}

Before you start

Create a function in a PHP runtime. For more information, see Create an event function.

Procedure

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

  2. In the top navigation bar, select a region. On the Functions page, click the function that you want to manage.

  3. On the function details page, click the Code tab. In the code editor, enter the preceding sample code and click Deploy.

    Note

    In the preceding sample code, the handler is the handler method in index.php. If the handler of your function is different, use the actual handler configurations.

  4. On the Code tab, click the down icon next to Test Function, click Configure Test Parameters from the drop-down list, enter the test parameters in the following sample code, and then click OK.

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

    After the function is executed, the content in JSON format is returned by the function, and values of key1, key2, and key3 are printed in the log output.

Example 2: Read and write OSS resources by using a temporary AccessKey pair

Sample code

You can use a temporary AccessKey pair that is provided by Function Compute to access Object Storage Service OSS. Sample code:

<?php

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

function handler($event, $context) {
    /*
      The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in Function Compute is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. 
      We recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account may be compromised. 
      In this example, the AccessKey ID and AccessKey secret are obtained from the 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"] specifies to obtain the temporary AccessKey pair from $context. This prevents hard encoding of 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 actual values of your resources.

Before you start

Procedure

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

  2. In the top navigation bar, select a region. On the Functions page, click the function that you want to manage.

  3. On the function details page, click the Code tab. In the code editor, enter the preceding sample code and click Deploy.

    Note

    In the preceding sample code, the handler is the handler method in index.php. If the handler of your function is different, use the actual handler configurations.

  4. Click Test Function.

    After the function is executed, the execution result hello world is returned.

Example 3: Run external commands

You can use a PHP program to create a fork process to run 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. Common methods for calling external commands include exec, system, and shell_exec.

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

<?php

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

Example 4: Use an HTTP trigger to invoke a function

Sample code

<?php

function handler($event, $context) {
  $logger = $GLOBALS['fcLogger'];
  $logger->info('hello world');
  $logger->info('receive event: ' . $event);
  
  try {
    $evt = json_decode($event, true);
    if (is_null($evt['body'])) {
      return "The request did not come from an HTTP Trigger, event: " . $event;
    }
    $body = $evt['body'];
    if ($evt['isBase64Encoded']) {
      $body = base64_decode($evt['body']);
    }
    return array(
      "statusCode" => 200,
      'headers' => array("Content-Type" => "text/plain"),
      'isBase64Encoded' => false,
      "body" => $body
    );
  } catch (Exception $e) {
      $logger->error("Caught exception: " . $e->getMessage());
      return "The request did not come from an HTTP Trigger, event: " . $event;
  }
}

Before you start

Use the preceding sample code to create a function in a PHP runtime. Create an HTTP trigger for the function. For more information, see Create an event function and Configure an HTTP trigger that invokes a function with HTTP requests.

Procedure

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

  2. In the top navigation bar, select a region. On the Functions page, click the function that you want to manage.

  3. On the function details page, click the Configurations tab. In the left-side navigation pane, click Triggers. On the Triggers page, obtain the public endpoint of the HTTP trigger.

  4. Run the following command in curl to invoke the function:

    curl -i "https://http-trigger-demo.cn-shanghai.fcapp.run" -d 'Hello FC!'
    Important
    • If the Authentication Method parameter of the HTTP trigger is set to No Authentication, you can use Postman or curl to invoke the function. For more information, see Procedure.

    • If the Authentication Method parameter of the HTTP trigger is set to Signature Authentication or JWT Authentication, you can use the signature method or JWT authentication method to invoke the function. For more information, see Authentication.

Possible errors

This sample code can be called by using an HTTP trigger or a custom domain name. If you use an API operation but the configured test parameters do not comply with request format requirements of HTTP triggers, an error is reported.

For example, the following response is returned if you invoke the function by clicking Test Function in the Function Compute console after you configure the request parameters as "Hello, FC!".

The request did not come from an HTTP Trigger, event: Hello FC!