sndwow/oss-sdk-php

阿里云OSS SDK for PHP


README

Latest Stable Version Build Status Coverage Status

中文README

概述

阿里云对象存储服务(OSS)是阿里云提供的云存储服务,具有海量存储、安全、低成本和高可靠性等特点。您可以通过调用API在任何时间、任何地点上传和下载数据,并通过网页控制台对数据进行简单的管理。OSS可以存储任何类型的文件,因此适用于各种网站、开发企业和开发者。

运行环境

  • PHP 5.3+
  • cURL 扩展

提示

  • 在Ubuntu上,您可以使用 apt-get 软件包管理器安装 PHP cURL 扩展sudo apt-get install php5-curl

安装OSS PHP SDK

  • 如果您使用 composer 管理项目依赖项,请在项目的根目录中运行以下命令

      composer require aliyuncs/oss-sdk-php
    

    您还可以在 composer.json 文件中声明对阿里云OSS SDK for PHP的依赖。

      "require": {
          "aliyuncs/oss-sdk-php": "~2.0"
      }
    

    然后,运行 composer install 安装依赖项。Composer依赖管理器安装后,将依赖项导入到您的PHP代码中

      require_once __DIR__ . '/vendor/autoload.php';
    
  • 您还可以直接下载打包的 PHAR 文件,并将其引入到代码中

      require_once '/path/to/oss-sdk-php.phar';
    
  • 下载SDK源代码,并将SDK目录下的 autoload.php 文件引入到代码中

      require_once '/path/to/oss-sdk/autoload.php';
    

快速使用

常见类

初始化OSSClient

SDK的OSS操作通过OSSClient类执行。下面的代码创建了一个OSSClient对象

<?php
$accessKeyId = "<AccessKeyID that you obtain from OSS>";
$accessKeySecret = "<AccessKeySecret that you obtain from OSS>";
$endpoint = "<Domain that you select to access an OSS data center, such as "oss-cn-hangzhou.aliyuncs.com>";
try {
    $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
} catch (OssException $e) {
    print $e->getMessage();
}

对象操作

对象是OSS上最基本的数据单元。您可以将对象简单地视为文件。下面的代码上传了一个对象

<?php
$bucket= "<Name of the bucket in use. Pay attention to naming conventions>";
$object = "<Name of the object in use. Pay attention to naming conventions>";
$content = "Hello, OSS!"; // Content of the uploaded file
try {
    $ossClient->putObject($bucket, $object, $content);
} catch (OssException $e) {
    print $e->getMessage();
}

桶操作

桶是您用来管理存储对象的空间。它是用户的对象管理单元。每个对象必须属于一个桶。以下代码创建了一个桶

<?php
$bucket= "<Name of the bucket in use. Pay attention to naming conventions>";
try {
    $ossClient->createBucket($bucket);
} catch (OssException $e) {
    print $e->getMessage();
}

处理返回结果

OSSClient提供了以下两种类型的返回数据从接口

  • Put和Delete接口:如果接口返回 null 且没有抛出 OSSException,则认为 PUTDELETE 操作成功。

  • Get和List接口:如果接口返回了所需数据且没有抛出 OSSException,则认为 GETLIST 操作成功。例如,

    <?php
    $bucketListInfo = $ossClient->listBuckets();
    $bucketList = $bucketListInfo->getBucketList();
    foreach($bucketList as $bucket) {
        print($bucket->getLocation() . "\t" . $bucket->getName() . "\t" . $bucket->getCreatedate() . "\n");
    }

在上面的代码中,$bucketListInfo 落入 'OSS\Model\BucketListInfo' 数据类型。

运行示例项目

  • 修改 samples/Config.php 以完成配置信息。
  • 运行 cd samples/ && php RunAll.php

运行单元测试

  • 运行 composer install 下载依赖库。

  • 设置环境变量。

      export OSS_ACCESS_KEY_ID=access-key-id
      export OSS_ACCESS_KEY_SECRET=access-key-secret
      export OSS_ENDPOINT=endpoint
      export OSS_BUCKET=bucket-name
    
  • 运行 php vendor/bin/phpunit

许可证

  • MIT

联系我们