bleeld / driver-alioss
阿里云 OSS SDK for PHP
1.0.2
2024-04-18 15:44 UTC
Requires
- php: >=5.3
README
中文README
概述
阿里云对象存储服务(OSS)是阿里云提供的一种云存储服务,具有大规模存储、安全、低成本和高可靠性等特点。您可以通过调用API在任何时间、任何地点上传和下载数据,并通过Web控制台对数据进行简单的管理。OSS可以存储任何类型的文件,因此适用于各种网站、开发企业和开发者。
运行环境
- PHP 5.3+
- cURL 扩展
提示
- 在Ubuntu中,您可以使用apt-get包管理器安装PHP cURL扩展:
sudo apt-get install php5-curl
。
安装OSS PHP SDK
-
如果您使用composer管理项目依赖项,请在项目的根目录中运行以下命令
composer require bleeld/driver-alioss
您还可以在
composer.json
文件中声明对阿里云OSS SDK for PHP的依赖。"require": { "bleeld/driver-alioss": "^1.0" }
然后运行
composer install
来安装依赖项。在Composer依赖项管理器安装后,在您的PHP代码中导入依赖项require_once __DIR__ . '/vendor/autoload.php';
-
下载SDK源代码,并将SDK目录下的
autoload.php
文件引入您的代码require_once '/vendor/bleeld/driver-alioss/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,则认为PUT和DELETE操作成功。
-
GET和LIST接口:如果接口返回所需数据且没有抛出OSSException,则认为GET和LIST操作成功。例如,
<?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