black-bits / bestcdn-sdk-php
BestCDN服务的PHP SDK
0.1.9
2018-09-17 21:19 UTC
Requires
- php: >=7.0.0
- guzzlehttp/guzzle: ^6.3
- illuminate/contracts: ^5.5
- illuminate/support: 5.1.*|5.2.*|5.3.*|5.4.*|5.5.*|5.6.*|5.7.*
Requires (Dev)
- phpunit/phpunit: ~6.0
README
用于与BestCDN一起工作的PHP SDK。
它包含可选的Laravel支持。
目前不稳定,即开发中,请自行决定是否使用。
如何安装
要将此包添加到您的应用程序中
composer require black-bits/bestcdn-sdk-php
使用Laravel时,需要发布配置
php artisan vendor:publish --provider="BlackBits\BestCdn\BestCdnServiceProvider"
如何使用
Laravel
使用Laravel,您可以使用SDK的多种方式。
使用外观
$key = "myPath/myFileName.ext"; // desired path on cdn $file = __DIR__ . "/file.ext"; // local absolute path $respose = BestCdn::putFile($key, $file);
使用依赖注入
例如在控制器内部
class FileController extends Controller { public function putFile(Request $request, BestCdn $cdn) { // ... $key = "myPath/myFileName.ext"; // desired path on cdn $file = __DIR__ . "/file.ext"; // local absolute path $respose = $cdn->putFile($key, $file); // ... } }
在其他框架或独立PHP中
如果您不使用Laravel框架,需要首先使用默认配置实例化基本类
$config = [ 'connections' => [ 'default' => [ "credentials" => [ "key" => "YourBestCdnProjectKey", // required "secret" => "YourBestCdnProjectSecret", // required ], "defaultRequestOptions" => [ "base_uri" => "https://management.bestcdn.io/", // required - e.g. sandbox(testing) or production endpoint "verify" => true, // optional - can be set to false for local testing (does not enforce SSL verification) ], ], ], "defaultConnection" => "default", // optional, if you configure multiple connections (multiple projects/testing/production) ]; $cdn = new BestCdn($config); $key = "myPath/myFileName.ext"; // desired path on cdn $file = __DIR__ . "/file.ext"; // local absolute path $respose = $cdn->putFile($key, $file);
发送请求
putFile()
在向CDN存储文件时,您需要提供所需的 key 和一个 file。
key 代表您项目命名空间内的子路径(CDN上的公共路径将结束于 /{project-name}-{customer-name}/{key})。
file 应该是一个指向文件的绝对路径。
$key = "myPath/myFileName.md"; // desired path on cdn $file = __DIR__ . "/README.md"; // local absolute path $respose = $cdn->putFile($key, $file);
putFileByUri()
通过URI向CDN存储文件时,您需要提供所需的 key 和 uri。CDN将从提供的URI下载文件。
key 代表您项目命名空间内的子路径(CDN上的公共路径将结束于 /{project-name}-{customer-name}/{key})。
uri 应该是文件的有效、公开可访问的URI。
$key = "myPath/myFileName.jpeg"; // desired path on cdn $uri = "https://static.pexels.com/photos/460797/pexels-photo-460797.jpeg"; // public uri $respose = $cdn->putFileByUri($key, $uri);
处理结果
请求成功后,您将获得如下响应数据
var_dump($response->data());
结果
array(1) {
["cdn_link"]=>
string(139) "https://staging.master.bestcdn.io/project_1-customer_01/example/image_profile/250x250_10.jpg"
}
要访问文件属性(如cdn_link),您可以使用如下便利方法
$response['cdn_link']; $response->get('cdn_link');
处理错误
我们提供标准化的异常以及默认的错误处理。
您可以这样处理常见错误
$cdn = new BestCdn($config); $key = "myPath/myFileName.md"; $file = __DIR__ . "/README.md"; $result = $cdn->putFile($key, $file); if ( $result->hasError() ) { print $result->statusCode(); print $result->message(); // ... abort mission! } // ... normal code
常见错误将包括常规、非关键错误,如尝试获取或删除不存在文件的详细信息。
如果错误需要处理(如认证错误等),将抛出异常。