本文介绍如何通过PHP SDK快速调用API执行创建服务、创建函数、调用函数、删除函数、删除服务等操作。
前提条件
PHP SDK示例
示例代码如下:
<?php
require_once __DIR__ . '/vendor/autoload.php';
use AliyunFC\Client;
fcClient = new Client([
"endpoint" => '<Your Endpoint>',
"accessKeyID" =>'<Your AccessKeyID>',
"accessKeySecret" =>'<Your AccessKeySecret>'
]);
// 创建服务。
fcClient->createService('service_name');
/*
创建函数。
当前目录有一个main.zip文件(main.php中有my_handler和my_initializer函数)。
设置环境变量{'testKey': 'testValue'}。
*/
fcClient->createFunction(
'service_name',
array(
'functionName' => $functionName,
'handler' => 'index.handler',
'runtime' => 'php7.2',
'memorySize' => 128,
'code' => array(
'zipFile' => base64_encode(file_get_contents(__DIR__ . '/main.zip')),
),
'description' => "test function",
'environmentVariables' => ['testKey' => 'testValue'],
)
);
//调用函数。
fcClient->invokeFunction('service_name', 'function_name');
/*
创建Initializer函数。
当前目录有一个main.zip文件(main.php中有my_handler和my_initializer函数)。
设置环境变量{'testKey': 'testValue'}。
*/
fcClient->createFunction(
'service_name_with_initializer',
array(
'functionName' => $functionName,
'handler' => 'index.handler',
'initializer' => 'index.initializer',
'runtime' => 'php7.2',
'memorySize' => 128,
'code' => array(
'zipFile' => base64_encode(file_get_contents(__DIR__ . '/main.zip')),
),
'description' => "test function with initializer",
'environmentVariables' => ['testKey' => 'testValue'],
)
);
//调用Initializer函数。
fcClient->invokeFunction('service_name_with_initializer', 'function_name');
//创建触发器,例如OSS触发器。
prefix = 'pre';
suffix = 'suf';
triggerConfig = [
'events' => ['oss:ObjectCreated:*'],
'filter' => [
'key' => [
'prefix' => $prefix,
'suffix' => $suffix,
],
],
];
sourceArn = 'acs:oss:cn-shanghai:12345678:bucketName';
invocationRole = 'acs:ram::12345678:role/aliyunosseventnotificationrole';
ret = $fcClient->createTrigger(
'service_name',
'function_name',
[
'triggerName' => 'trigger_name',
'triggerType' => 'oss',
'invocationRole' => $invocationRole,
'sourceArn' => $sourceArn,
'triggerConfig' => $triggerConfig,
]
);
//根据输入参数调用函数。
fcClient->invokeFunction('service_name', 'function_name', $payload='hello_world');
// 调用函数,异步模式。
fcClient->invokeFunction('service_name', 'function_name', 'hello world', ['x-fc-invocation-type' => 'Async']);
// 获取服务列表。
fcClient->listServices();
//获取符合prefix和limit参数描述的函数列表。
fcClient->listFunctions('service_name', ['prefix' => 'hello', "limit" => 2]);
//获取触发器列表。
fcClient->listTriggers('service_name', 'function_name');
//删除触发器。
fcClient->deleteTrigger('service_name', 'function_name', 'trigger_name');
//删除函数。
fcClient->deleteFunction('service_name', 'function_name');
//删除服务。
fcClient->deleteService('service_name');