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 isindex.handler
, Function Compute loads thehandler
method that is defined inindex.php
and executes the function fromhandler
.$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 specifiedevent
parameter. You can parseevent
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.
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
Log on to the Function Compute console. In the left-side navigation pane, click Functions.
In the top navigation bar, select a region. On the Functions page, click the function that you want to manage.
On the function details page, click the Code tab. In the code editor, enter the preceding sample code and click Deploy.
NoteIn the preceding sample code, the handler is the
handler
method inindex.php
. If the handler of your function is different, use the actual handler configurations.On the Code tab, click the 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 } }
Click Test Function.
After the function is executed, the content in JSON format is returned by the function, and values of
key1
,key2
, andkey3
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 ofrandombucket
in OSS.NoteReplace
endpoint
,bucket
,object
, andfilePath
with actual values of your resources.
Before you start
Configure a role that has permissions to access OSS. For more information, see Grant Function Compute permissions to access other Alibaba Cloud services.
Create a function in a PHP runtime. For more information, see Create an event function.
Procedure
Log on to the Function Compute console. In the left-side navigation pane, click Functions.
In the top navigation bar, select a region. On the Functions page, click the function that you want to manage.
On the function details page, click the Code tab. In the code editor, enter the preceding sample code and click Deploy.
NoteIn the preceding sample code, the handler is the
handler
method inindex.php
. If the handler of your function is different, use the actual handler configurations.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
Log on to the Function Compute console. In the left-side navigation pane, click Functions.
In the top navigation bar, select a region. On the Functions page, click the function that you want to manage.
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.
Run the following command in curl to invoke the function:
curl -i "https://http-trigger-demo.cn-shanghai.fcapp.run" -d 'Hello FC!'
ImportantIf 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!