Todos os produtos
Search
Central de documentação

Object Storage Service:Gerenciamento de ciclo de vida com PHP

Última atualização: Jul 08, 2026

Este tópico descreve como usar o PHP SDK V2 para gerenciar o recurso de ciclo de vida de buckets.

Informações básicas

No OSS, nem todos os dados carregados exigem acesso frequente. No entanto, devido a requisitos de conformidade ou arquivamento, alguns dados ainda precisam ser preservados em armazenamento frio. Com base nas necessidades do seu negócio, escolha:

  1. Regras de ciclo de vida baseadas na hora da última modificação: Quando determinados dados não são modificados por um longo período e não precisam mais ser retidos, use esta regra para excluí-los em lote ou convertê-los para tipos de armazenamento frio, liberando espaço de armazenamento.

  2. Regras de ciclo de vida baseadas na hora do último acesso: Se você deseja que o OSS monitore automaticamente os padrões de acesso aos dados para identificar dados frios e converter dinamicamente os tipos de armazenamento, ative esta regra. O OSS identifica automaticamente os dados sem acesso recente e os converte para um armazenamento frio mais econômico, realizando o tiering de dados quentes e frios e reduzindo custos de armazenamento.

Considerações

  • Antes de configurar regras de ciclo de vida baseadas na hora da última modificação ou na hora do último acesso, certifique-se de entender esse recurso. Para obter mais informações, consulte Regras de ciclo de vida baseadas na hora da última modificação e Regras de ciclo de vida baseadas na hora do último acesso.

  • O código de exemplo neste tópico usa o ID de região cn-hangzhou da China (Hangzhou) e utiliza o endpoint público por padrão. Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use o endpoint interno. Para obter mais informações sobre o mapeamento entre regiões e endpoints suportados pelo OSS, consulte Regiões e endpoints do OSS.

  • Para configurar regras de ciclo de vida, é necessária a permissão oss:PutBucketLifecycle. Para visualizar regras de ciclo de vida, é necessária a permissão oss:GetBucketLifecycle. Para excluir regras de ciclo de vida, é necessária a permissão oss:DeleteBucketLifecycle. Para obter mais informações, consulte Conceder permissões personalizadas a um usuário RAM.

Configurar regras de ciclo de vida

Os códigos a seguir fornecem exemplos de regras de ciclo de vida configuradas com base na hora da última modificação e na hora do último acesso dos dados. Após concluir a configuração, caso precise modificar uma ou mais regras de ciclo de vida, consulte Como modifico uma ou mais configurações de regra de ciclo de vida?.

Configurar uma regra de ciclo de vida baseada na hora da última modificação para alterar as classes de armazenamento de objetos

O código a seguir exemplifica como configurar uma regra de ciclo de vida baseada na hora da última modificação para alterar as classes de armazenamento de objetos em um bucket.

<?php

// Include the autoload file to load dependencies
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;
use AlibabaCloud\Oss\V2\Models\LifecycleConfiguration;

// Specify descriptions for command line parameters
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located', 'required' => True], // (Required) Specify the region in which the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS', 'required' => False], // (Optional) Specify the endpoint that can be used by other services to access OSS.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Specify the name of the bucket.
];

// Generate a list of long options to parse the command-line parameters
$longopts = \array_map(function ($key) {
    return "$key:"; // Add a colon after each parameter to indicate that a value is required
}, array_keys($optsdesc));

// Parse the command-line parameters
$options = getopt("", $longopts); 

// Check whether the required parameters are missing
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help"; // Prompt the user for missing required parameters
        exit(1); 
    }
}

// Obtain the values of the command-line parameters
$region = $options["region"]; // The region in which the bucket is located
$bucket = $options["bucket"]; // The name of the bucket

// Use environment variables to load the AccessKey ID and AccessKey secret
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configuration of the SDK
$cfg = Oss\Config::loadDefault();

// Specify the credential provider
$cfg->setCredentialsProvider($credentialsProvider);

// Specify the region
$cfg->setRegion($region);

// Specify the endpoint if an endpoint is provided
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

// Create an OSSClient instance
$client = new Oss\Client($cfg);

// Define a lifecycle rule to convert objects whose names contain the log/ prefix to the IA storage class after 30 days
$lifecycleRule = new Oss\Models\LifecycleRule(
    prefix: 'log/', // The prefix of the object
    transitions: array(
        new Oss\Models\LifecycleRuleTransition(
            days: 30, // The conversion time is 30 days
            storageClass: 'IA' // The target storage class is IA
        )
    ),
    id: 'rule', // The ID of the rule
    status: 'Enabled' // The status of the rule is enabled
);

// Create a lifecycle configuration object and add the lifecycle rule
$lifecycleConfiguration = new LifecycleConfiguration(
    rules: array($lifecycleRule)
);

// Create a request object to set the lifecycle of the bucket and pass in the lifecycle configuration
$request = new Oss\Models\PutBucketLifecycleRequest(
    bucket: $bucket,
    lifecycleConfiguration: $lifecycleConfiguration
);

// Call the putBucketLifecycle method to set the lifecycle rules for the bucket
$result = $client->putBucketLifecycle($request);

// Display the returned result
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code
    'request id:' . $result->requestId . PHP_EOL // The unique identifier of the request
);

Configurar uma regra de ciclo de vida baseada na hora da última modificação para converter a classe de armazenamento de objetos, excluindo objetos cujos nomes contêm prefixos específicos ou que possuem tags específicas

O código a seguir exemplifica como especificar que objetos em um bucket — exceto aqueles cujos nomes contêm o prefixo log, objetos com a tag key1=value1 e objetos que atendem aos requisitos de tamanho especificados — sejam convertidos para a classe de armazenamento IA 30 dias após a última modificação e expirem após 100 dias.

<?php

// Include the autoload file to load dependencies
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;
use AlibabaCloud\Oss\V2\Models\LifecycleConfiguration;

// Specify descriptions for command line parameters
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located', 'required' => True], // (Required) Specify the region in which the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS', 'required' => False], // (Optional) Specify the endpoint that can be used by other services to access OSS.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Specify the name of the bucket.
];

// Generate a list of long options to parse the command-line parameters
$longopts = \array_map(function ($key) {
    return "$key:"; // Add a colon after each parameter to indicate that a value is required
}, array_keys($optsdesc));

// Parse the command-line parameters
$options = getopt("", $longopts); 

// Check whether the required parameters are missing
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help"; // Prompt the user for missing required parameters
        exit(1); 
    }
}

// Obtain the values of the command-line parameters
$region = $options["region"]; // The region in which the bucket is located
$bucket = $options["bucket"]; // The name of the bucket

// Use environment variables to load the AccessKey ID and AccessKey secret
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configuration of the SDK
$cfg = Oss\Config::loadDefault();

// Specify the credential provider
$cfg->setCredentialsProvider($credentialsProvider);

// Specify the region
$cfg->setRegion($region);

// Specify the endpoint if an endpoint is provided
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

// Create an OSSClient instance
$client = new Oss\Client($cfg);

// Define a lifecycle rule to convert objects whose names contain the log/ prefix to the IA storage class after 30 days
$lifecycleRule = new Oss\Models\LifecycleRule(
    id: 'rule', // The ID of the rule
    status: 'Enabled', // The status of the rule is enabled
    prefix: 'logs', // The prefix of the object
    transitions: array(
        new Oss\Models\LifecycleRuleTransition(
            days: 30, // The conversion time is 30 days
            storageClass: 'IA', // The target storage class is IA
            isAccessTime: false // Set to false, based on the last modified time policy
        )
    ),
    filter: new Oss\Models\LifecycleRuleFilter( // Define filter conditions
        objectSizeGreaterThan: 500, // Set greater than 500 bytes
        objectSizeLessThan: 1000, // Set less than 1000 bytes
        not: new Oss\Models\LifecycleRuleNot( // Define exclusion conditions
            prefix: 'logs/log', // Exclude objects with the log prefix
            tag: new Oss\Models\Tag( // Define tag conditions
                key: 'key1',
                value: 'value1'
            )
        )
    ),
    expiration: new Oss\Models\LifecycleRuleExpiration(
        days: 100 // The expiration time is 100 days
    )
);

// Create a lifecycle configuration object and add the lifecycle rule
$lifecycleConfiguration = new LifecycleConfiguration(
    rules: array($lifecycleRule)
);

// Create a request object to set the lifecycle of the bucket and pass in the lifecycle configuration
$request = new Oss\Models\PutBucketLifecycleRequest(
    bucket: $bucket,
    lifecycleConfiguration: $lifecycleConfiguration
);

// Call the putBucketLifecycle method to set the lifecycle rules for the bucket
$result = $client->putBucketLifecycle($request);

// Display the returned result
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code
    'request id:' . $result->requestId . PHP_EOL // The unique identifier of the request
);

Configurar uma regra de ciclo de vida baseada na hora do último acesso para alterar as classes de armazenamento de objetos

O exemplo de código abaixo demonstra a configuração de uma regra de ciclo de vida baseada na hora do último acesso para modificar as classes de armazenamento de objetos em um bucket.

<?php

// Include the autoload file to load dependencies
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;
use AlibabaCloud\Oss\V2\Models\LifecycleConfiguration;

// Specify descriptions for command line parameters
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located', 'required' => True], // (Required) Specify the region in which the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS', 'required' => False], // (Optional) Specify the endpoint that can be used by other services to access OSS.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Specify the name of the bucket.
];

// Generate a list of long options to parse the command-line parameters
$longopts = \array_map(function ($key) {
    return "$key:"; // Add a colon after each parameter to indicate that a value is required
}, array_keys($optsdesc));

// Parse the command-line parameters
$options = getopt("", $longopts); 

// Check whether the required parameters are missing
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help"; // Prompt the user for missing required parameters
        exit(1); 
    }
}

// Obtain the values of the command-line parameters
$region = $options["region"]; // The region in which the bucket is located
$bucket = $options["bucket"]; // The name of the bucket

// Use environment variables to load the AccessKey ID and AccessKey secret
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configuration of the SDK
$cfg = Oss\Config::loadDefault();

// Specify the credential provider
$cfg->setCredentialsProvider($credentialsProvider);

// Specify the region
$cfg->setRegion($region);

// Specify the endpoint if an endpoint is provided
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

// Create an OSSClient instance
$client = new Oss\Client($cfg);

// Define a lifecycle rule to convert objects whose names contain the log/ prefix to the IA storage class after 30 days
$lifecycleRule = new Oss\Models\LifecycleRule(
    prefix: 'log/', // The prefix of the object
    transitions: array(
        new Oss\Models\LifecycleRuleTransition(
            days: 30, // The conversion time is 30 days
            storageClass: 'IA', // The target storage class is IA
            IsAccessTime: 'true', // Whether to trigger the conversion based on the access time
            ReturnToStdWhenVisit: 'false' // Keep as IA storage when accessed again
        )
    ),
    id: 'rule', // The ID of the rule
    status: 'Enabled' // The status of the rule is enabled
);

// Create a lifecycle configuration object and add the lifecycle rule
$lifecycleConfiguration = new LifecycleConfiguration(
    rules: array($lifecycleRule)
);

// Create a request object to set the lifecycle of the bucket and pass in the lifecycle configuration
$request = new Oss\Models\PutBucketLifecycleRequest(
    bucket: $bucket,
    lifecycleConfiguration: $lifecycleConfiguration
);

// Call the putBucketLifecycle method to set the lifecycle rules for the bucket
$result = $client->putBucketLifecycle($request);

// Display the returned result
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code
    'request id:' . $result->requestId . PHP_EOL // The unique identifier of the request
);

Visualizar regras de ciclo de vida

O código a seguir mostra como visualizar as informações contidas nas regras de ciclo de vida.

<?php

// Include the autoload file to load dependencies
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Specify descriptions for command line parameters
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located', 'required' => True], // (Required) Specify the region in which the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS', 'required' => False], // (Optional) Specify the endpoint that can be used by other services to access OSS.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Specify the name of the bucket.
];

// Generate a list of long options to parse the command-line parameters
$longopts = \array_map(function ($key) {
    return "$key:"; // Add a colon after each parameter to indicate that a value is required
}, array_keys($optsdesc));

// Parse the command-line parameters
$options = getopt("", $longopts); 

// Check whether the required parameters are missing
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help"; // Prompt the user for missing required parameters
        exit(1); 
    }
}

// Obtain the values of the command-line parameters
$region = $options["region"]; // The region in which the bucket is located
$bucket = $options["bucket"]; // The name of the bucket

// Use environment variables to load the AccessKey ID and AccessKey secret
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configuration of the SDK
$cfg = Oss\Config::loadDefault();

// Specify the credential provider
$cfg->setCredentialsProvider($credentialsProvider);

// Specify the region
$cfg->setRegion($region);

// Specify the endpoint if an endpoint is provided
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

// Create an OSSClient instance
$client = new Oss\Client($cfg);

// Create a request object to get the lifecycle of the bucket
$request = new Oss\Models\GetBucketLifecycleRequest(bucket: $bucket);

// Call the getBucketLifecycle method to get the lifecycle rules of the bucket
$result = $client->getBucketLifecycle($request);

// Display the returned result
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code
    'request id:' . $result->requestId . PHP_EOL . // The unique identifier of the request
    'lifecycle:' . var_export($result->lifecycleConfiguration, true) . PHP_EOL // The content of the lifecycle rules
);

Excluir regras de ciclo de vida

O código abaixo ilustra como excluir regras de ciclo de vida configuradas para examplebucket. Caso queira excluir uma ou mais regras de ciclo de vida específicas, consulte Como excluo uma ou mais regras de ciclo de vida?.

<?php

// Include the autoload file to load dependencies
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Specify descriptions for command line parameters
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Specify the endpoint that can be used by other services to access OSS.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Specify the name of the bucket.
];

// Generate a list of long options to parse the command-line parameters
$longopts = \array_map(function ($key) {
    return "$key:"; // Add a colon after each parameter to indicate that a value is required
}, array_keys($optsdesc));

// Parse the command-line parameters
$options = getopt("", $longopts); 

// Check whether the required parameters are missing
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help"; // Prompt the user for missing required parameters
        exit(1); 
    }
}

// Obtain the values of the command-line parameters
$region = $options["region"]; // The region in which the bucket is located
$bucket = $options["bucket"]; // The name of the bucket

// Use environment variables to load the AccessKey ID and AccessKey secret
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configuration of the SDK
$cfg = Oss\Config::loadDefault();

// Specify the credential provider
$cfg->setCredentialsProvider($credentialsProvider);

// Specify the region
$cfg->setRegion($region);

// Specify the endpoint if an endpoint is provided
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

// Create an OSSClient instance
$client = new Oss\Client($cfg);

// Create a request object to delete the lifecycle rules of the bucket
$request = new Oss\Models\DeleteBucketLifecycleRequest(bucket: $bucket);

// Call the deleteBucketLifecycle method to delete the lifecycle rules of the bucket
$result = $client->deleteBucketLifecycle($request);

// Display the returned result
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code
    'request id:' . $result->requestId . PHP_EOL // The unique identifier of the request
);

Referências

  • Para obter mais informações sobre a operação de API usada para configurar regras de ciclo de vida, consulte PutBucketLifecycle.

  • Para detalhes sobre a operação de API usada para visualizar regras de ciclo de vida, consulte GetBucketLifecycle.

  • Para saber mais sobre a operação de API usada para excluir regras de ciclo de vida, consulte DeleteBucketLifecycle.