This topic describes how to install and use the PHP software development kit (SDK). The GetProject operation of Function AI is used as an example. For more information about the GetProject API, see GetProject - Query a project.
Prerequisites
API calls to Alibaba Cloud OpenAPI require an AccessKey pair. An AccessKey pair provides full access to your Alibaba Cloud account and poses a high security risk if leaked. We recommend that you use an AccessKey pair that belongs to a Resource Access Management (RAM) user and grant the RAM user only the minimum required permissions.
Configure the AccessKey pair in an environment variable
For more information, see Configure environment variables on Linux, macOS, and Windows.
Environment requirements
1. PHP 5.6 or later
2. Install Composer globally on your system.
The PHP version that you use to install the SDK with Composer must be the same as or earlier than the PHP version at runtime. For example, if you install the SDK in a PHP 7.2 environment, the generated vendor folder is compatible only with PHP 7.2 or later. If you copy the folder to a PHP 5.6 environment, dependency incompatibility issues may occur.
If you cannot complete the installation due to network issues, you can run the following command to use the full Alibaba Cloud Composer mirror.
composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/Installation method
You can copy and run the following command in your terminal to install the Function AI SDK:
composer require alibabacloud/devs-20230714Use the SDK
1. Initialize the client
All OpenAPI calls are made through a client object. Before you can make an API call, you must initialize the client. The client can be initialized in several ways. This example shows how to initialize the client using an AccessKey pair. For more information about other initialization methods, see Manage access credentials.
<?php
require_once 'vendor/autoload.php';
use AlibabaCloud\SDK\Devs\V20230714\Devs;
use Darabonba\OpenApi\Models\Config;
class Sample
{
public static function createClient()
{
$config = new Config([
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
"accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
"accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
// Required. The endpoint of the Devs service. For more information, see https://api.aliyun.com/product/Devs.
"endpoint" => "devs.cn-hangzhou.aliyuncs.com",
]);
return new Devs($config);
}
}2. Create a request object for the operation
Before you make a call, you can view the API documentation for the operation to obtain parameter information.
Unlike some operations that require you to create a complex request object, the main parameter for the GetProject operation, `projectName`, is passed directly as a string.
// Prepare the name of the project to query.
$projectName = "my-devs-project"; // Replace this with the actual name of your project.
// Create a runtime configuration object.
$runtime = new RuntimeOptions();
3. Make the call
When you call an OpenAPI operation, you can set runtime parameters, such as timeout and proxy configurations. For more information, see Advanced configurations.
The naming convention for the response object of an operation is `{APIName}Response`. For example, the response object for the GetProject operation is `GetProjectResponse`.
// Make the request.
$response = $client->getProjectWithOptions($projectName, $headers, $runtime);
// Print the result.
echo json_encode($response->body, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n";
4. Handle exceptions
The PHP SDK provides detailed exception categorization. To ensure the robustness of your program, you must handle potential exceptions when you call an API operation.
TeaError: This exception type primarily handles business errors returned by the API, such as invalid parameters or resources that do not exist. You can usegetCode()andgetMessage()to retrieve specific error messages from the server for debugging.Exception: Other exceptions, such as network issues.
For more information about exception handling, see Exception handling.
To ensure system robustness and stability, you must handle exceptions by propagating them correctly, recording logs, and attempting to recover from them.
5. Complete example
<?php
// Import the Composer autoloader file.
require_once __DIR__ . '/vendor/autoload.php';
// Import all required classes.
use AlibabaCloud\SDK\Devs\V20230714\Devs;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\Dara\Models\RuntimeOptions;
use AlibabaCloud\Tea\Exception\TeaError;
/**
* This is an example of how to use the Alibaba Cloud Devs SDK to query project information.
*/
class GetProjectSample
{
public static function main()
{
try {
// 1. Initialize the client.
// The SDK automatically retrieves credentials from the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.
$config = new Config([
"accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
"accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
"endpoint" => "devs.cn-hangzhou.aliyuncs.com",
]);
$client = new Devs($config);
// 2. Prepare the parameters for the API call.
$projectName = "my-devs-project"; // Replace this with the actual name of your project.
$runtime = new RuntimeOptions();
$headers = [];
// 3. Make the API call.
$response = $client->getProjectWithOptions($projectName, $headers, $runtime);
// 4. Handle a successful response.
echo " API call successful!\n";
// Use the standard PHP json_encode() function to print the object, and use JSON_PRETTY_PRINT to format the output.
echo json_encode($response->body, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n";
} catch (Exception $error) {
// 5. Handle exceptions.
echo " API call failed!\n";
if ($error instanceof TeaError) {
echo " Error Code: " . $error->getCode() . "\n";
echo " Error Message: " . $error->getMessage() . "\n";
echo " Request ID: " . ($error->data['RequestId'] ?? 'N/A') . "\n";
} else {
echo " An unknown exception occurred: " . $error->getMessage() . "\n";
}
}
}
}
// Run the main function.
GetProjectSample::main();More information
In addition to the method described in this topic, you can also use generalized calls to call Function AI OpenAPI operations. For more information, see Generalized calls.