Upgrade OSS SDK for PHP from 1.0 to 2.0

更新时间:
复制 MD 格式

OSS SDK for PHP 2.0 is a complete rewrite of 1.0. The core call pattern—$client->operation($request)—remains the same, but the client initialization, import namespace, signature algorithm, and several API names have changed. This guide walks you through each change so you can upgrade with minimal risk.

What's different at a glance

Review the key changes before you begin to estimate your upgrade effort.

AreaV1V2Migration impact
PHP versionPHP 5.3 or laterPHP 7.4 or later (PHP 8.0 or later for bucket operations)Breaking — upgrade PHP first
Composer packagealiyuncs/oss-sdk-phpalibabacloud/oss-v2Breaking — update composer.json
Import namespaceuse OSS\OssClient;use AlibabaCloud\Oss\V2 as Oss;Breaking — update all imports
Default signatureV1 signatureV4 signature (region required)Breaking — add region to config
Endpoint configRequired (manual)Auto-generated from regionNew behavior — manual config optional
Configuration styleScattered across multiple locationsCentralized in Config class with set* helpersSimplification
API namingInconsistentStandard <OperationName>Request / <OperationName>Result patternSimplification
Presigned URL operation$ossClient->signUrl() — returns URL string$client->presign() — returns URL, HTTP method, expiration, and signed headersBreaking — update call sites
Retry on failureCustom retry logic requiredAutomatic retry for failed HTTP requestsNew behavior — remove custom retry code
Transfer managersNoneUploader, Downloader, CopierNew feature
PaginatorNoneBuilt-in paginatorNew feature

Prerequisites

Before you begin, make sure you have:

  • PHP 7.4 or later installed (PHP 8.0 or later for bucket-related operations)

  • Composer installed

  • A list of the OSS features and API operations your application currently uses

Step 1: Prepare the environment

Review your existing code

Identify all files that import OSS\OssClient, record every OSS API operation your app calls, and note any custom retry or error-handling logic — these will be the main areas to update.

Install V2 alongside V1

Run V1 and V2 side by side during migration so you can test incrementally without downtime.

Install V2 with Composer:

composer require alibabacloud/oss-v2

Alternatively, declare the dependency in composer.json and run composer install:

"require": {
    "alibabacloud/oss-v2": "*"
}

To install from a PHAR file instead, download the release from GitHub and include it:

require_once '/path/to/alibabacloud-oss-php-sdk-v2-{version}.phar';

Set up a test environment

Before touching production code, configure a separate test environment with test data and test cases for the upgraded code.

Step 2: Update imports

The V2 SDK moved to a new repository (alibabacloud-oss-php-sdk-v2) with a restructured codebase organized by feature module.

Module pathDescription
src/Core SDK — basic and advanced API operations
src/CredentialsAccess credentials
src/RetryRetry mechanism
src/SignerSignature
src/AnnotationTag and XML conversion annotation
src/CryptoClient-side encryption
src/ModelsRequest and response objects
src/PaginatorPaginator
src/ExceptionException handling
src/TypesTypes

Replace the V1 import with the V2 namespace in every file:

// V1
require_once 'vendor/autoload.php';
use OSS\OssClient;

// V2
require_once 'vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;

Step 3: Update client initialization

Key differences in V2:

  • Configuration is centralized in the Config class. Call Oss\Config::loadDefault() to create a config object, then use set* helpers to override individual settings.

  • V4 signature is the default. Specify a region ID — V2 uses it to automatically generate the endpoint, so you no longer need to set the endpoint manually for public access.

  • SSL verification is disabled with setDisableSSL(true) instead of setUseSSL(false).

// V1
require_once 'vendor/autoload.php';
use OSS\OssClient;

$provider = new \OSS\Credentials\EnvironmentVariableCredentialsProvider();
$endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
$config = array(
    "provider"         => $provider,
    "endpoint"         => $endpoint,
    "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
    "region"           => "cn-hangzhou"
);
$ossClient = new OssClient($config);
$ossClient->setUseSSL(false); // Disable SSL verification
// V2
require_once 'vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;

$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider);
$cfg->setRegion('cn-hangzhou');         // Required — V2 derives the endpoint from this
$cfg->setConnectTimeout(20);            // HTTP connection timeout, in seconds
$cfg->setReadWriteTimeout(60);          // Read/write timeout, in seconds
$cfg->setDisableSSL(true);             // Disable SSL verification

$client = new Oss\Client($cfg);

For the full list of configuration options, see Configure an OSSClient instance.

Step 4: Update API calls

Key differences in V2:

  • Every operation follows the naming pattern <OperationName>, with a matching <OperationName>Request input class and <OperationName>Result output class.

  • Pass a typed request object instead of positional arguments.

  • Object bodies are wrapped with Oss\Utils::streamFor().

Method signatures:

public function <operationName>(Models\<OperationName>Request $request, array $args = []): Models\<OperationName>Result
public function <operationName>Async(Models\<OperationName>Request $request, array $args = []): \GuzzleHttp\Promise\Promise

Example — upload an object:

// V1
$ossClient->putObject('examplebucket', 'exampleobject.txt', 'example data');
// V2
$client->putObject(
    new Oss\Models\PutObjectRequest(
        bucket: 'examplebucket',
        key:    'exampleobject.txt',
        body:   Oss\Utils::streamFor('example data'),
    ),
);

For the complete list of basic API operations, see Basic API operations.

Step 5: Update advanced API calls (optional)

Generate a presigned URL

Key differences in V2:

  • The operation is renamed from signUrl() to presign().

  • The request parameter reuses the same <OperationName>Request type as the corresponding API operation.

  • The result includes the presigned URL, the HTTP method, the expiration time, and the signed request headers (not just the URL string as in V1).

// V1
$url = $ossClient->signUrl(
    'examplebucket',
    'exampleobject.txt',
    60,                     // Expiration: 60 seconds from now
    OssClient::OSS_HTTP_GET
);
printf("Sign URL: %s\n", $url);
// V2
$result = $client->presign(
    new Oss\Models\GetObjectRequest(
        bucket: 'examplebucket',
        key:    'exampleobject.txt',
    ),
    args: [
        // Set expiration to 60 seconds from now (UTC)
        'expiration' => (new \DateTime('now', new \DateTimeZone('UTC')))->add(new DateInterval('PT60S')),
    ],
);

print(
    'URL: '        . $result->url                             . PHP_EOL .
    'Method: '     . $result->method                          . PHP_EOL .
    'Expires: '    . var_export($result->expiration, true)    . PHP_EOL .
    'Headers: '    . var_export($result->signedHeaders, true) . PHP_EOL
);

The PresignResult structure:

final class PresignResult
{
    public ?string    $method;
    public ?string    $url;
    public ?\DateTime $expiration;
    public ?array     $signedHeaders;
}

For the complete sample code for uploading an object with a presigned URL, see Use a presigned URL to upload an object.

Use transfer managers

V2 introduces dedicated transfer managers for uploads, downloads, and copy operations. These handle multipart logic, retries, and concurrency automatically.

Upload a file with Uploader:

$uploader = $client->newUploader();
$result = $uploader->uploadFile(
    new Oss\Models\PutObjectRequest(
        bucket: 'examplebucket',
        key:    'exampleobject.txt',
    ),
    filepath: '/local/dir/example.txt',
);
printf(
    'Status: %s, Request ID: %s' . PHP_EOL,
    $result->statusCode,
    $result->requestId
);

Download a file with Downloader:

$downloader = $client->newDownloader();
$downloader->downloadFile(
    new Oss\Models\GetObjectRequest(
        bucket: 'examplebucket',
        key:    'exampleobject.txt',
    ),
    filepath: '/local/dir/example.txt',
);

Copy an object with Copier:

$copier = $client->newCopier();
$result = $copier->copy(
    new Oss\Models\CopyObjectRequest(
        bucket:       'examplebucket',
        key:          'dest-object.txt',
        sourceBucket: 'src-bucket',
        sourceKey:    'src-object.txt',
    )
);
printf(
    'Status: %s, Request ID: %s' . PHP_EOL,
    $result->statusCode,
    $result->requestId
);

For more information, see:

Step 6: Verify the upgrade

Test incrementally — start with a small, isolated module and expand coverage after each module passes.

Unit tests

Write test cases for each upgraded module that cover:

  • Core CRUD operations — create resources, read state, update data, delete resources

  • Boundary conditions — very large or very small payloads, edge-case inputs

  • Error handling — network timeouts, invalid inputs, and other failure scenarios

Compatibility tests

Verify that V2 works correctly across your full stack:

  • Internal systems — confirm V2 is compatible with your existing architecture

  • Third-party services — test any external APIs or services that interact with OSS

  • Runtime environments — test across all operating systems and PHP versions your app targets

Performance tests

After upgrading, compare application performance against pre-upgrade baselines:

  1. Record key metrics with V1 — response time and throughput under representative load.

  2. Run the same tests with V2 under identical conditions.

  3. If V2 shows unexpected degradation, tune setConnectTimeout, setReadWriteTimeout, and concurrency settings.

What's next