Use Alibaba Cloud SDKs for PHP in an IDE

Updated at:
Copy as MD

Get started with Alibaba Cloud SDKs for PHP in an IDE on Windows. This example uses Visual Studio (VS) Code.

Prerequisites

Use an SDK

Use a sample project provided in OpenAPI Explorer

Note

Sample projects may not be available for all API operations. If you cannot download one, see the Use an SDK in an existing project section.

  1. Go to OpenAPI Explorer and search for the API operation to call. For example, to call the DescribeRegions API operation of ECS, enter DescribeRegions in the search bar and click the API name in the search results to open the API debugging page.

  2. On the Parameters tab, configure the required parameters. Review the information on the Document tab on the right side of the debugging page to understand the usage notes and parameter descriptions. Pay attention to billing-related information.

    On the Documentation tab, the Request Parameters table lists the name, type, description, and example value for each parameter, such as InstanceChargeType, ResourceType, and AcceptLanguage. The Response Parameters are listed below.

  3. On the SDK Sample Code tab on the right side of the debugging page, select the PHP programming language and click Download Project to download the sample project package. Then, decompress the package.

    Select SDK version V2.0 (Recommended), select PHP on the language tab, and then click Download Project.

  4. Open the decompressed package in VS Code and run the composer install command in the terminal to install the required dependencies.

    You may encounter the following error when you run the composer install command:

    Your requirements could not be resolved to an installable set of packages.
      Problem 1
        - Root composer.json requires alibabacloud/ecs-20140526 ^4.1.6 -> satisfiable by alibabacloud/ecs-20140526[4.1.6].
        - alibabacloud/ecs-20140526 4.1.6 requires alibabacloud/tea-utils ^0.2.20 -> found alibabacloud/tea-utils[dev-master, 0.1.0, ..., 0.2.19] but it does not match the constraint.

    To fix this error, modify the version constraint of the alibabacloud/ecs-20140526 dependency in the composer.json file.

    "alibabacloud/ecs-20140526": "^4.1"
  5. Run the php src/Sample.php command in the terminal to run the sample code. If "statusCode":200 is returned in the response, the call is successful.

    PS D:\xxx\download\e11baaaa2-4f02-4671-8432-2423be5a5a6f-PHP> php src/Sample.php
    [2024-07-03T09:59:56.716282+00:00] tea-console-log.INFO: {"headers":{"Date":["Wed, 03 Jul 2024 10:00:00 GMT"],"Content-Type":["application/json;charset=utf-8"],"Connection":["keep-alive"],"Keep-Alive":["timeout=25"],"Vary":["Accept-Encoding"],"Access-Control-Allow-Origin":["*"],"Access-Control-Expose-Headers":["*"],"x-acs-request-id":["3BA5A6C3-B296-5895-914A-8147910DE781"],"x-acs-trace-id":["086d8bd615f72d4d27daa5a7a7b4b89a"],"ETag":["22UU6WnEtZKE9S/VA80fvig"]},"statusCode":200,"body":{"Regions":{"Region":[{"LocalName":"China (Qingdao)","RegionEndpoint":"ecs.cn-qingdao.aliyuncs.com","RegionId":"cn-qingdao"},{"LocalName":"China (Beijing)","RegionEndpoint":"ecs.cn-beijing.aliyuncs.com","RegionId":"cn-beijing"},{"LocalName":"China (Zhangjiakou)","RegionEndpoint":"ecs.cn-zhangjiakou.aliyuncs.com","RegionId":"cn-zhangjiakou"},{"LocalName":"China (Hohhot)","RegionEndpoint":"ecs.cn-huhehaote.aliyuncs.com","RegionId":"cn-huhehaote"},{"LocalName":"China (Ulanqab)","RegionEndpoint":"ecs.cn-wulanchabu.aliyuncs.com","RegionId":"cn-wulanchabu"},{"LocalName":"China (Hangzhou)","RegionEndpoint":"ecs.aliyuncs.com","RegionId":"cn-hangzhou"},{"LocalName":"China (Shanghai)","RegionEndpoint":"ecs.cn-shanghai.aliyuncs.com","RegionId":"cn-shanghai"},...]},"RequestId":"3BA5A6C3-B296-5895-914A-8147910DE781"}} [] []

Use an SDK in an existing project

  1. Obtain the SDK: Visit the SDK Center and select the cloud product you want to use. This example uses ECS. For SDK Version, select V2.0, and for Language, select PHP.

    The SDK page lists the environment requirements: PHP 5.6 or later and a globally installed Composer. To install the SDK from Packagist, run the composer require alibabacloud/ecs-20140526 4.1.7 command. To use the Alibaba Cloud Composer mirror, run composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/.

  2. Open VS Code. In the top navigation bar, choose File > Open Folder. Create and select a project folder or select an existing project folder. In this example, a folder named phpprojects is created and selected.

  3. Copy the SDK installation command and run it in the terminal.

  4. In the EXPLORER panel, right-click the blank area and select New File to create a PHP file. Name the file demo.php.

  5. Initialize a client. You must initialize a client before calling Alibaba Cloud API operations. In this example, an ECS client is initialized.

    Important
    1. You must use an AccessKey pair to complete identity verification when you initialize the client. In this case, you must obtain an AccessKey pair in advance. For more information about how to obtain an AccessKey pair, see Create an AccessKey.

    2. After you obtain the AccessKey pair of a RAM user, you must configure the AccessKey pair in environment variables. For more information, see Configure environment variables in Linux, macOS, and Windows.

    3. For more information about how to configure the endpoint, see Endpoints.

    <?php
    use AlibabaCloud\Credentials\Credential\Config;
    use AlibabaCloud\SDK\Ecs\V20140526\Ecs;
    class Sample
    {
        /**
         * Create an ECS client instance.
         * This method initializes and returns an ECS client object that can be used to perform ECS-related operations.
         * It configures the client by reading the AccessKey ID and AccessKey secret from environment variables, which ensures secure storage and access of sensitive information.
         * 
         * @return Ecs A configured ECS client instance.
         */
        public static function createClient()
        {
            // Create a configuration object.
            $config = new Config([
                "accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), // Obtain the AccessKey ID of a RAM user from an environment variable.
                "accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"), // Obtain the AccessKey secret of a RAM user from an environment variable.
                "endpoint" => "ecs.cn-hangzhou.aliyuncs.com" // Set the endpoint for the ECS service.
            ]);
            // Use this configuration to create a new Ecs client instance.
            return new Ecs($config);
        }
    }
  6. Call the API. Review the API Documentation for the target API. The following example calls the `DescribeRegions` API of ECS.

    Note

    Each API has a separate request object that follows the `${APIName}${Request}` naming convention, such as `DescribeRegionsRequest`.

    <?php
    require_once 'vendor/autoload.php';
    use AlibabaCloud\SDK\Ecs\V20140526\Ecs;
    use AlibabaCloud\SDK\Ecs\V20140526\Models\DescribeRegionsRequest;
    use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
    use Darabonba\OpenApi\Models\Config;
    class Sample
    {
        /**
         * Create an ECS client instance.
         * This method initializes and returns an ECS client object that can be used to perform ECS-related operations.
         * It configures the client by reading the AccessKey ID and AccessKey secret from environment variables, which ensures secure storage and access of sensitive information.
         * 
         * @return Ecs A configured ECS client instance.
         */
        public static function createClient()
        {
            // Create a configuration object.
            $config = new Config([
                "accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), // Obtain the AccessKey ID of a RAM user from an environment variable.
                "accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"), // Obtain the AccessKey secret of a RAM user from an environment variable.
                "endpoint" => "ecs.cn-hangzhou.aliyuncs.com" // Set the endpoint for the ECS service.
            ]);
            // Use the preceding configuration to create a new Ecs client instance.
            return new Ecs($config);
        }
        /**
         * 
         * This function demonstrates how to use the SDK client to call the DescribeRegions API operation.
         * It creates a client instance, constructs a request object, and attempts to call the API operation.
         * If the call fails, the exception is caught and the error message is printed.
         */
        public static function main()
        {
            // Create an SDK client instance.
            $client = self::createClient();
            // Create a DescribeRegionsRequest request object without passing any parameters.
            $describeRegionsRequest = new DescribeRegionsRequest([]);
            // Create a RuntimeOptions instance without passing any parameters.
            $runtime = new RuntimeOptions([]);
            try {
                // Call the API operation using the client's describeRegionsWithOptions method.
                // A try-catch block is used to handle potential exceptions.
                $result = $client->describeRegionsWithOptions($describeRegionsRequest, $runtime);
                print_r($result);
            } catch (Exception $error) {
                // This is for demonstration purposes only. In a production environment, do not ignore exceptions.
                var_dump($error->message);
            }
        }
    }
    Sample::main();
  7. Handle exceptions. In production, never ignore exceptions. Report exceptions, record logs, and perform retries to ensure the robustness and stability of your system. For more information, see Handle an exception.

    <?php
    require_once 'vendor/autoload.php';
    use AlibabaCloud\SDK\Ecs\V20140526\Ecs;
    use AlibabaCloud\SDK\Ecs\V20140526\Models\DescribeRegionsRequest;
    use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
    use Darabonba\OpenApi\Models\Config;
    class Sample
    {
        /**
         * Create an ECS client instance.
         * This method initializes and returns an ECS client object that can be used to perform ECS-related operations.
         * It configures the client by reading the AccessKey ID and AccessKey secret from environment variables, which ensures secure storage and access of sensitive information.
         * 
         * @return Ecs A configured ECS client instance.
         */
        public static function createClient()
        {
            // Create a configuration object.
            $config = new Config([
                "accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), // Obtain the AccessKey ID of a RAM user from an environment variable.
                "accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"), // Obtain the AccessKey secret of a RAM user from an environment variable.
                "endpoint" => "ecs.cn-hangzhou.aliyuncs.com" // Set the endpoint for the ECS service.
            ]);
            // Use the preceding configuration to create a new Ecs client instance.
            return new Ecs($config);
        }
        /**
         * 
         * This function demonstrates how to use the SDK client to call the DescribeRegions API operation.
         * It creates a client instance, constructs a request object, and attempts to call the API operation.
         * If the call fails, the exception is caught and the error information is printed.
         */
        public static function main()
        {
            // Create an SDK client instance.
            $client = self::createClient();
            // Create a DescribeRegionsRequest request object without passing any parameters.
            $describeRegionsRequest = new DescribeRegionsRequest([]);
            // Create a RuntimeOptions instance without passing any parameters.
            $runtime = new RuntimeOptions([]);
            try {
                // Call the API operation using the client's describeRegionsWithOptions method.
                // A try-catch block is used to handle potential exceptions.
                $result = $client->describeRegionsWithOptions($describeRegionsRequest, $runtime);
                print_r($result);
            } catch (Exception $error) {
                if ($error instanceof TeaError) {
                    // This is for demonstration purposes only. In a production environment, do not ignore exceptions.
                    print_r("message:" . $error->getMessage() . "\n");
                    print_r("code:" . $error->getCode() . "\n");
                    print_r($error->data);
                } elseif ($error instanceof TeaUnableRetryError) {
                    // This is for demonstration purposes only. In a production environment, do not ignore exceptions.
                    print_r($error->getLastException());
                } else {
                    // This is for demonstration purposes only. In a production environment, do not ignore exceptions.
                    print_r("message:" . $error->getMessage());
                }
            }
        }
    }
    Sample::main();

FAQ

  • What do I do if the error "cURL error 60: SSL certificate problem: unable to get local issuer certificate" occurs when I call an API operation?

    • Download a trusted certificate authority (CA) certificate, such as one from Mozilla. For more information, see CA certificates extracted from Mozilla.

    • Configure the SSL certificate path for PHP. In the php.ini file, find the curl.cainfo parameter, set its value to the absolute path of the CA certificate, and remove the leading semicolon (;).

    • Restart the PHP service.

References

Advanced references