As a recap from my previous article, CloudFiles is a an online storage service for your static content.

作为我上一篇文章的回顾,CloudFiles是一项针对您的静态内容的在线存储服务。

Rackspace provides a Software Development Kit (SDK) for multiple programming languages. They store their PHP SDK on GitHub. The PHP SDK requires PHP 5 with the following modules: cURL, FileInfo and mbstring.

Rackspace提供了用于多种编程语言的软件开发套件(SDK)。 他们将PHP SDK存储在GitHub上 。 PHP SDK需要具有以下模块PHP 5:cURL,FileInfo和mbstring。

In this tutorial we are going to review use of the PHP SDK with CloudFiles. Not all parts of the API will be covered but you will get a great start.

在本教程中,我们将回顾将PHP SDK与CloudFiles一起使用。 并非涵盖API的所有部分,但您将获得一个良好的开端。

Once you download the SDK you only need the following files and folders:

下载SDK后,您仅需要以下文件和文件夹:

  • share/分享/
  • cloudfiles.phpcloudfiles.php
  • cloudfiles_exceptions.phpcloudfiles_exceptions.php
  • cloudfiles_http.phpcloudfiles_http.php

您的第一次飞行 (Your first flight)

Starting off we have some basic tasks. We need to load the cloudfiles.php file, authenticate with CloudFiles, and create a connection using our authentication token.

首先,我们有一些基本任务。 我们需要加载cloudfiles.php文件,使用CloudFiles进行身份验证,并使用我们的身份验证令牌创建连接。

<?php
$your_username = 'jeffk';
$your_api_key = 'longrandomapikey';require 'cloudfiles.php';/*** Authenticate using your Rackspace Cloud username and your API key obtained from the control panel**/
$auth = new CF_Authentication($your_username, $your_api_key);/*** If you use Cloud Files in the U.K. use**/
$auth = new CF_Authentication($your_username, $your_api_key, null, UK_AUTHURL);$auth->authenticate();/*** Now we create the connection with our CF_Authentication instance**/
$connection = new CF_Connection($auth);
?>

It’s that simple. Now that we’re connected our next step is to interact with a container.

就这么简单。 现在我们已连接,下一步是与容器进行交互。

货柜 (Containers)

We can create, delete, list, and open different containers. To interact with any container we are going to use our $connection object we created above.

我们可以创建,删除,列出和打开不同的容器。 为了与任何容器交互,我们将使用上面创建的$ connection对象。

Lets go through creating a container that stores our files.

让我们来创建一个存储文件的容器。

<?php
/*** To create a container, use the $connection variable and call the create_container method. If the container* already exists it will return a container instance and NOT overwrite the container.**/
$images = $connection->create_container("images");
?>

This will return a container object. In the example we named it $images. This will be used to manipulate the container along with any objects in it. If you need to interact with any objects in a container you have to use the create_container method to to access it. Since the container already exists, it will return the instance and it won’t overwrite it.

这将返回一个容器对象。 在示例中,我们将其命名为$images 。 这将用于操纵容器及其中的任何对象。 如果需要与容器中的任何对象进行交互,则必须使用create_container方法来访问它。 由于该容器已经存在,它将返回该实例,并且不会覆盖该实例。

Now, deleting a container that is no longer needed. Note: you cannot remove a container that has objects (files) in it. If there are files inside it you must remove them all prior to deleting the container. At the end of the article there is a snippet for removing all objects and then deleting the container.

现在,删除不再需要的容器。 注意:您不能删除其中包含对象(文件)的容器。 如果其中包含文件,则必须先删除所有文件,然后再删除容器。 在文章的末尾有一个摘录,用于删除所有对象,然后删除容器。

<?php
/*** To delete a container call the delete_container method.**/
$connection->delete_container("images");
?>

With these actions done, how about getting the containers? If you want an array of your containers with various information you can use the get_containers method.

完成这些操作后,如何获得容器? 如果您想要一个包含各种信息的容器数组,则可以使用get_containers方法。

<?php
/*** Get an array of your available containers and display them.**/
$containers = $connection->get_containers();foreach($containers as $container) {echo 'Name: '. $container->name;echo 'Number of Objects: '. $container->count;echo 'Bytes Stores: '.$container->bytes;
}
?>

If you only want the names of the containers we have the list_containers method:

如果只需要容器的名称,则可以使用list_containers方法:

<?php
$containers = $connection->list_containers();
print_r($containers); // Returns Array([0] => "images")
?>

将其提供给CDN (Making it available to the CDN)

By default all containers are private. To make them available on the Content Delivery Network and accessible by a url, we have to tell the API to make the container public. Naturally we can return it to private if need be.

默认情况下,所有容器都是私有的。 为了使它们在Content Delivery Network上可用并可以通过url访问,我们必须告诉API将容器公开。 当然,如果需要,我们可以将其归还给私人。

<?php
/*** To make a container public use the containers instance and call make_public. You can      * optionally include a timestamp for how long the file is cached on the CDN network. The    * default is 86400 (1 day)* Calling this method returns the URI the container is available at.**/
$public_uri = $images->make_public();/*** You can also get the URI by calling the cdn_uri or cdn_ssl_uri attributes**/
$uri => $images->cdn_uri;
$https_uri = $images->cdn_ssl_uri;/*** To set a public container private you can call make_private. However, all the files in this container will still be available until the cache time expires.**/
$images->make_private();
?>

物体物体 (Objects, objects, objects)

To create an object we have to carry over our container instance and use the create_object method with the name of the file. Once we do that, we have to send the contents of the file. There are two ways to do that. The easiest way is to use the load_from_filename method so it will gather all the information for us. The second way we specify the file and the size.

要创建一个对象,我们必须继承我们的容器实例,并使用带有文件名的create_object方法。 完成后,我们必须发送文件的内容。 有两种方法可以做到这一点。 最简单的方法是使用load_from_filename方法,以便它将为我们收集所有信息。 第二种方法是指定文件和大小。

<?php
$avatar = $images->create_object('jeffs_avatar.jpg');
$avatar->load_from_filename('/home/user/photos/jeffs_avatar.jpg');$file_name = '/home/user/photos/jeffs_avatar.jpg');
$file_size = (float) sprintf("%u", filesize($file_name));
$fp = open($file_name, 'r');
$avatar->write($fp, $file_size);?>

To get a private object we can use the steam method. This works really well for protecting content. It’s not just limited to images either, if you wanted to restrict access to a pdf document for your members only, this would be ideal.

要获取私有对象,我们可以使用steam方法。 这对于保护内容确实非常有效。 它也不仅限于图像,如果您只想限制成员访问pdf文档,那将是理想的选择。

<?php
$img = $images->get_object('jeff.jpg');header('Content-Type: '.$img->content_type);
$output = fopen("php://output", "w");
$img->stream($output);
fclose($output);
?>

To delete an object we need to use our container and call the delete_object method.

要删除对象,我们需要使用我们的容器并调用delete_object方法。

<?php
$images->delete_object('jeff.jpg');
?>

整理起来。 一些工作实例 (Finishing Up. A few working examples)

Here we have an example of scanning a folder for .jpg files and uploading them to Rackspace Cloud Files.

在这里,我们有一个扫描文件夹中的.jpg文件并将其上传到Rackspace Cloud Files的示例。

<?php$api_username = 'jeffk';
$api_key = 'myapikey';$file_path = '/home/user/images';require 'cloudfiles.php';$auth = new CF_Authentication($api_username, $api_key);
$auth->authenticate();$connection = new CF_Connection($auth);
$images = $connection->create_container("images");
$url = $images->make_public();
echo 'The url is '.$url;/*** Now that we have our connection and access to the container lets get our files.**/
if ($h = opendir($file_path)) {/*** We just opened the directory and now we are going to scan that directory for any files**/while (false !== ($file = readdir($h))) {/*** Now we are going to get the extension of the file. If it matches "jpg" then we are going to upload it.* Otherwise we are going to ignore it.**/$get_extension = explode('.', $file);if ($get_extension[count($get_extension)-1]=='jpg') {/*** Lets create the object and send it to CloudFiles**/$img = $images->create_object($file);$img->load_from_filename($file_path.'/'.$file);/** Now we delete the image so we don't try to upload it again if we rerun the script **/unset($img);}}/*** Close the handler for good measure**/closedir($h);
}
?>

The next example is deleting a container that already contains objects.

下一个示例是删除已经包含对象的容器。

<?php
$objects = $images->list_objects();
if (count($objects)>0) {foreach($objects as $o) {$images->delete_object($o);}
}
$connection->delete_container("images");?>

What I provided here were a few basic examples. A few things you might add in are returning the url to the objects, error handling, or even making sure there are 1 or more objects waiting to be uploaded before connecting.

我在这里提供的是一些基本示例。 您可能要添加的一些内容是将URL返回给对象,错误处理,甚至确保在连接之前有1个或多个对象等待上载。

其他需要知道的 (Additional Need to Know)

If you get an error as seen below you need to update your ca certificates, refer to your OS manual or web host to get them upgraded. After I successfully tested in my development environment I ran into this issue in production.

如果出现如下所示的错误,则需要更新ca证书,请参阅操作系统手册或网络主机以升级它们。 在开发环境中成功测试后,我在生产中遇到了这个问题。

* About to connect() to lon.auth.api.rackspacecloud.com port 443
* Trying 212.64.148.13... * connected
* Connected to lon.auth.api.rackspacecloud.com (212.64.148.13) port 443
* successfully set certificate verify locations:
* CAfile: /etc/pki/tls/certs/ca-bundle.crt
CApath: none
* SSL certificate problem, verify that the CA cert is OK. Details:
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
* Closing connection #0
PHP Fatal error: Uncaught exception 'InvalidResponseException' with message     'Unexpected response (): ' in /usr/share/php/cloudfiles/cloudfiles.php:212
Stack trace:
#0 /var/www/html/cloudtest.php(18): CF_Authentication->authenticate()
#1 {main}
thrown in /usr/share/php/cloudfiles/cloudfiles.php on line 212Fatal error: Uncaught exception 'InvalidResponseException' with message 'Unexpected     response (): ' in /usr/share/php/cloudfiles/cloudfiles.php:21

Next, Rackspace uses exceptions when errors occur. Wrapping your code in try{ } catch() { } blocks will allow you to get the error message instead of an “ Uncaught exception….” Listed below you can see the different exception classes they use and that they only extend the Exception class provided by php.

接下来,Rackspace在发生错误时使用异常。 将代码包装在try {} catch(){}块中将使您获得错误消息,而不是“ Uncaught exception…”。 在下面列出的列表中,您可以看到它们使用的不同异常类,并且它们仅扩展了php提供的Exception类。

class SyntaxException extends Exception { }
class AuthenticationException extends Exception { }
class InvalidResponseException extends Exception { }
class NonEmptyContainerException extends Exception { }
class NoSuchObjectException extends Exception { }
class NoSuchContainerException extends Exception { }
class NoSuchAccountException extends Exception { }
class MisMatchedChecksumException extends Exception { }
class IOException extends Exception { }
class CDNNotEnabledException extends Exception { }
class BadContentTypeException extends Exception { }
class InvalidUTF8Exception extends Exception { }
class ConnectionNotOpenException extends Exception { }

If you were to attempt to remove a container that still had objects in it, the software development kit would throw a NonEmptyContainerException exception that you have to watch for.

如果要尝试删除仍然有对象的容器,则软件开发工具包将引发必须注意的NonEmptyContainerException异常。

<?php
/**
* Try to run the code
**/try {$connection->delete_container("images");
}
/**
* If there was an exception thrown, catch it and display the message
**/catch(NonEmptyContainerException $e) {echo $e->getMessage();
}

If our container wasn’t empty it would display “Container must be empty prior to removing it”. If you didn’t catch the error it would provide an output such as:

如果我们的容器不是空的,则会显示“容器在移走之前必须为空”。 如果您没有发现错误,它将提供如下输出:

Fatal error: Uncaught exception 'NonEmptyContainerException' with message 'Container    must be empty prior to removing it.' in /Users/kreitje/Development/test/    cloudfiles.php:560 Stack trace: #0 /Users/kreitje/Development/test/index.php(25):   CF_Connection->delete_container('images') #1 {main} thrown in /Users/kreitje/   Development/test/cloudfiles.php on line 560

If developing an application that customers will interact with you will want to catch any exception. Sometimes the error that gets displayed shows sensitive information. Above, you can see where my files are stored. Depending on the error, it’s possible that your API credentials may be displayed on the browser page.

如果开发客户可以与您进行交互的应用程序,则将希望捕获任何异常。 有时显示的错误显示敏感信息。 在上方,您可以看到我的文件存储在哪里。 根据错误,您的API凭证可能会显示在浏览器页面上。

In the software development kit there’s a docs folder that goes over these methods, along with a few extra ones. Now that you have the basics down and know where the documentation is, I challenge you to create a project that interacts with Rackspace CloudFiles.

在软件开发工具包中,有一个docs文件夹介绍这些方法,以及一些其他方法。 现在您已经掌握了基础知识,并且知道文档在哪里,现在我挑战您创建一个与Rackspace CloudFiles交互的项目。

Artush Images on Shutterstock

Shutterstock上的Artush Images

翻译自: https://www.sitepoint.com/using-the-rackspace-php-sdk-2/

使用Rackspace PHP SDK相关推荐

  1. php for ios sdk,Rackspace Cloud SDK for PHP入门指南

    Rackspace Cloud SDK for PHP入门指南 Rackspace Cloud SDK for PHP 是一个用来帮助PHP开发者更方便的开发基于OpenStack和Rackspace ...

  2. 使用第三方SDK(如微信、qq、快看、头条等),调用接口405 Method Not Allowed

    使用第三方SDK(如微信.qq.快看.头条等),调用接口405 Method Not Allowed 错误描述:postman请求正常,但客户端调用后接口没有反应,但返回了405错误. 解决方法:第三 ...

  3. 消除安卓SDK更新时的“https://dl-ssl.google.com refused”异常的方法

    消除安卓SDK更新时的"https://dl-ssl.google.com refused"异常的方法 消除安卓SDK更新时的"https://dl-ssl.google ...

  4. HiCar SDK概述

    HiCar SDK概述 HUAWEI HiCar SDK 是 HUAWEI HiCar(以下简称 HiCar )为汽车硬件设备提供的软件开发工具包,为汽车硬件厂商接入 HiCar 提供应用 API 接 ...

  5. NVIDIA空中导航SDK改造5G通信

    NVIDIA空中导航SDK改造5G通信 Transforming Next-Generation Wireless with 5T for 5G and the NVIDIA Aerial SDK N ...

  6. 在Lumen中引入钉钉SDK

    最近在用Lumen开发钉钉企业内部应用,需要调用钉钉的SDK.不得不说,钉钉开发文档写的真是感人,开发的时候那是相当刺激.在使用SDK的时候遇到不少坑,钉钉的文档写的不是很详细,记录下在Laravel ...

  7. HarmonyOS开发工具DevEcoStudio 的下载以及运行(包含下载开发工具,sdk,模拟机,以及运行第一个应用你好,世界)

    开发工具下载 首先打开HarmonyOS 官网 地址链接 向下滑动一下就能看到开发工具DevEcoStudio 了,点击下载 下载之后是一个压缩包(我这里下载的windos版本的) 解压之后有一个.e ...

  8. Android SDK 路径修改

    今天早上感觉电脑有点卡 就修改了SDK的安装路径 这里记录下现在的修改方法 现在android studio 安装的时候sdk  默认下载路径是c盘  AppDate -->android -- ...

  9. android 调用百度sdk点位当前城市

    参考地址: http://lbsyun.baidu.com/index.php?title=android-locsdk/guide/get-location/address 百度的sdk定位 dem ...

最新文章

  1. 静态路由和默认路由的配置实例
  2. lattice diamond 3.7安装破解
  3. MonkeyRunner 的使用一
  4. VS2008显示代码行号
  5. SpringBoot异常处理的简单理解
  6. 运营系统的前世今生(1)
  7. P1368-工艺【最小表示法】
  8. 【渝粤题库】国家开放大学2021春2402外国文学题目
  9. 2.10 stack
  10. HDU 4291 A Short problem 矩阵快速幂 循环节
  11. 无类域间路由CIDR
  12. 电大考的是职称英语同计算机,最新电大统考计算机应用基础真题选择题详细分析小抄.doc...
  13. 1121: [POI2008]激光发射器SZK
  14. 用laravel开发php,使用 PhpStorm开发Laravel项目
  15. 使用re正则匹配网络请求到的正文内容,筛选出jpg图片链接
  16. C++ GBD调试
  17. go vender 的环境搭建和使用
  18. 手绘标记视频标题文字介绍ae模板
  19. GDOC CEO Musk Shing出席“链接未来”区块链全球人才交流会
  20. 微服务_服务网关(Gateway)

热门文章

  1. 874 计算机科学专业基础综合 大纲,2017年四川大学874计算机科学专业基础综合之计算机操作系统考研题库...
  2. poj 3271 LilyPad
  3. 在vue项目中webpack打包后字体不生效
  4. 【MySQL】MySQL如何合并多行数据,行转列,group_concat 多行合并
  5. 【路径规划】基于遗传算法求解OD对流量优化问题附matlab代码
  6. 怎样重启Juniper网络设备的mgd进程?
  7. 应用VAR模型时的15个注意点
  8. Java中字符加数字会产生什么?
  9. KAA平台的配置使用
  10. 认识计算机学情分析方案,知学情 研教法 夯基础 重效果-------计算机应用工程系召开2014级学情分析会...