快轉到主要內容

Drupal7 中Restful模组应用简单介绍

·1918 字·4 分鐘
Y Cheung
作者
Y Cheung
Blogger, Programer & Traveler.
目錄

安装并启用Restful Module
#

  • Restful 2.x 下载
  • drush 安装 drush dl restfuldrush en restful

自定义RESTFUL API模组
#

  • 可参考restful里的范例 sites/all/modules/restful/modules/restful_example 或者测试文件内容 sites/all/modules/restful/tests

模组文件结构
#

1custom_restfulapi/
2├─ src/
3│  ├─ Plugin/
4│  │  ├─ resource/
5│  │  │  ├─ entity/
6│  │  │  │  ├─ Testentity__1_0.php
7├─ custom_restfulapi.info
8├─ custom_restfulapi.module

API RESOURCES要放在src/Plugin下。 *.info 和 *.module 的内容跟其他自定义模组的相差无几,方法一样,此处从略。

1name = RESTful custom
2description = Custom RESTful resource.
3core = 7.x
4dependencies[] = restful
5
6registry_autoload[] = PSR-4

建立API端点(API endpoint)
#

此处以建立暴露entity的API端点为例,一般地,在Plugin/resource里创建entity文件夹(非必须),然后新建一个PHP文件Testentity__1_0.php,文件内容大致如下:

 1<?php
 2
 3namespace Drupal\custom_restfulapi\Plugin\resource\entity;
 4
 5use Drupal\restful\Plugin\resource\ResourceEntity;
 6use Drupal\restful\Plugin\resource\ResourceInterface;
 7
 8/**
 9 * Class Testentity__1_0
10 * @package Drupal\custom_restfulapi\Plugin\resource\entity
11 *
12 * @Resource(
13 *   name = "Testentity:1.0",
14 *   description = "A simple testapi.",
15 *   resource = "testentity",
16 *   label = "Test entity ",
17 *   authenticationTypes = {
18 *   "token"
19 *   },
20 *   authenticationOptional = TRUE,
21 *   dataProvider = {
22 *     "entityType": "sampleentitytype",
23 *     "bundles": {
24 *       "samplebundle","samplebundle2"
25 *     },
26 *   },
27 *   majorVersion = 1,
28 *   minorVersion = 0
29 * )
30 */
31
32class Testentity__1_0 extends ResourceEntity implements ResourceInterface
33{
34    /**
35     * Overrides ResourceEntity::publicFields().
36     * @return array
37     */
38    protected function publicFields()
39    {
40        $public_fields = parent::publicFields();
41        $public_fields['customfieldname'] = array(
42            'property'=>'field_number',
43            'process_callbacks' => array(
44                array($this,'toFloat'),
45            ),
46        );
47        return $public_fields;
48    }
49
50    /**
51     * @param $value
52     * @return float
53     */
54    public function toFloat($value){
55        $value = (float)$value;
56        return $value;
57    }
58
59}

Restful 使用了注释(Annotation)定义资源。

  • resource=定义了API接口的URL,比如此处定义的API接口即为 example.com\api\testentity
  • authenticationTypes定义验证方式,默认的是HTTP BASIC AUTH,当启用了模组 RESTful token authentication时就可以用本例中的值启用Token authentication。获取token的方法参考这里,简而言之
    • GET /api/login-token
    • header参数(Authorization:Basic b2M6b2MxMjM0),b2M6b2MxMjM0为“用户名:密码”BASE64编码后的字符串;
    • 响应:
1{
2  "access_token": "D8uD2xjDtlT8ym0BiM-n4R-cssRACxgf34xsBQpgGKw",
3  "type": "Bearer",
4  "expires_in": 86400,
5  "refresh_token": "jhHpCr3FubMsSyE-9B6wPgtPMeQn2u34-P4blDSiXrw"
6}
  • authenticationOptional若值为TRUE则不验证,直接可以获取资源,这个设置在开发和测试的时候很好用;
  • dataProvider定义了数据来源,具体到了bundle,可以多个bundle;
  • majorVersionminorVersion 定义了版本号。

在类 Class Testentity__1_0 中,我们使用 publicFields() 定义输出json中的entity各字段的key和value值,默认输出id,labelself字段,如果不需要暴露可以在return $public_fieldsunset它们,比如这样:

1 unset($public_fields['self'],$public_fields['label']);
2 $public_fields['id']['methods']=array();

可以对每个字段值格式化,过滤等进行处理,添加一个回调函数即可,比如本例中的:

1'process_callbacks'=> array(
2        array($this,'toFloat'),
3      ),

返回的json范例

 1{
 2    "data": [
 3        {
 4            "id":1,
 5            "label":"The Beatles",
 6            "self":"http:\/\/example.com\/api\/v0.1\/testentity\/1",
 7            "customfieldname":"19.22"
 8        },
 9        {
10            "id":2,
11            "label":"Chuck Berry",
12            "self":"http:\/\/example.com\/api\/v0.1\/testentity\/2",
13            "customfieldname":"19.55"
14        }
15    ],
16    "count":2,
17    "self":{
18        "title":"Self",
19        "href":"http:\/\/example.com\/api\/v0.1\/testentity"
20    }
21}

自定义resource内容
#

有时候需要返回的json数据并不是单纯的输出entity,可能还需要经过汇总计算等等,这就只能自定义resource内容了。使用 controllersInfo()函数自定义控制器,然后在自定义function中输出任意array,Restful模组会帮你格式化成相应的json数据包含在data中输出。

Restful的过滤功能个人觉得参数传起来太麻烦了,比如这样子的:https://example.com/api/articles?filter[integer_multiple][value][0]=5&filter[integer_multiple][value][1]=10&filter[integer_multiple][operator][0]=">"&filter[integer_multiple][operator][0]="=" 一大长传太恶心了,好在自定义的function中可以直接用 $this->request->getParsedInput()来获取URL中传入的参数。

一个简单的范例,可以将上面的Testentity__1_0类改写为:

 1class Testentity__1_0 extends ResourceEntity implements ResourceInterface {
 2   /**
 3     * Override ResourceEntity::controllersInfo()
 4     * @return array
 5     */
 6    public function controllersInfo()
 7    {
 8        return array('^.*$' => array(
 9            RequestInterface::METHOD_GET => 'customviewEntity',
10        ));
11    }
12
13    public function customviewEntity($sid){
14        $input = $this->request->getParsedInput();
15        $query = $this->getDataProvider()->EFQObject();
16        if(!empty($input)){
17            $start_time = $input['start'];
18            $end_time = $input['end'];
19            $result = $query -> entityCondition('entity_type','sampleentitytype')
20                ->entityCondition('bundle','samplebundle')
21                ->propertyCondition('person_id',$sid)
22                ->propertyCondition('created',array($start_time,$end_time),'BETWEEN')
23                ->execute();
24        }else{
25            $result = $query -> entityCondition('entity_type','sampleentitytype')
26                ->entityCondition('bundle','samplebundle')
27                ->propertyCondition('person_id',$sid)
28                ->execute();
29        }
30        $jsonarray = array();
31        $sum = 0;
32        if(!empty($result)){
33            $e = entity_load('sampleentitytype',array_keys($result['sampleentitytype']));
34            foreach ($e as $entity) {
35                $sum += $entity->field_fp['und']['0']['value'];
36            }
37            $jsonarray = array('psersonid'=>$sid,'sum'=>$sum);
38        }
39        return $jsonarray;
40    }
41}

这样就能通过 http://example.com/testentity/$id?start=$starttime&end=$endtime 这样的URL来通过一段时间来过滤内容了,并且默认传$id的位置还能被定义成其他非数字字符,自由度很高。

小结
#

Restful 模组确实上手有点困难,相关内容杂七杂八并且重复性较高,多数时候还是只能直接读module的代码来去看它怎么用。另外1.x版本和2.x版本相也是很大的,要小心….


更多详情请参考 官方wiki 文档

相關文章

Krpano Panoramic Video Embed Wordpress plugin

·380 字·1 分鐘
krpano 做 Panoramic Video 的時候很麻煩(官網說明太簡單),要自己改一堆東西然後上傳,然後再用iframe的方式在wordpress 文章或者頁面中加載,一整個就煩透了。於是用空閒時間順手做了這個插件,稍微簡化了一下流程。 軟體版本: # Wordpress 版本 4.3.1 Krpano 版本 1.18 插件下載: # Github BOX 安裝插件: # 文件解壓縮至 /wp-content/plugins/ 將你購買的krpano程序中相應的文件替換掉本插件中的文件,包括 /krpano/krpano.js 和 /krpano/krpano.swf ,(本插件中的文件源自未授權demo版,請自行購買授權)。 登錄wordpress後台,並激活插件 使用插件: # 將 Panoramic Video 壓制成 1920x960 和 1024x512 尺寸,推薦WEBM格式或MP4格式 製作 Panoramic Video 封面縮略圖兩張,尺寸分別為1920x960 像素 和 1024x512 像素 將視頻和圖片通過FTP上傳至 /krpano/video 文件夾中 點擊編輯器上的按鈕(如下圖所示)在需要嵌入Panoramic Video的地方插入代碼 務必完整填寫完所有表單(如下圖示) 5. 如需自定義XML,文件放在 /krpano/xml 中

Unity3D製作Cardboard全景VR應用

·1481 字·3 分鐘
本文中所使用的軟體 # Unity3D 5.1.2f1 (官方下載地址) Unity 版的 Cardboard SDK(官方下載地址) Java SE Development Kit 8 (官方下載地址) Android SDK (官方下載地址) PTGui (可選) 操作步驟 # 新建 Unity3D 工程 # 在Unity中新建一個工程: VRtour

全景圖製作軟體PTGui與Kolor AutopanoGiga之初體驗

·1027 字·3 分鐘
全景图(panorama)是一种广角图,可以以画作、照片、影片、三维模型的形式存在。 全景,指於球體的空間狀態,視角涵蓋地平線+/-各180°,垂直+/-各90°,就立方體的空間狀態,即為上下前後左右六個面完全包含。尤於水平角度為360°,垂直為180°,能表達這種模式的照片有很多種,又跟球面的投影有關(類似繪製世界地圖的投影,但是是內投影)。 1

DokuWiki 安装及使用

·609 字·2 分鐘
最近搭建了一个私密wiki用来管理知识碎片及资料等,Y.Cheung 选择了DokuWiki这款开源wiki引擎。 DokuWiki优点: # 轻便、简洁、可扩展性强 免数据库,data直接保存为txt 用户众多,方便搜寻及使用各种资源 支持markdown语法 支持ACL权限控制 基于PHP DokuWiki缺点: # 无移动平台客户端(在github上有找到这个开发项目但已经停止更新好几年了) 默认界面简陋难看,提供下载的模版也很丑 使用上手有一定的学习成本 安装DokuWiki: # 在下载页面选择你要的版本、语言、插件等后下载.tgz文件到本地,再上传至Server 解压缩安装包后在浏览器中访问 http://yourdomain/path_to_dokuwiki/install.php,根据提示进行即可 对文件及文件夹进行权限设置,特别是data文件夹的权限 启用默认的.htaccess 文件,按需要去除文件内的#符号 更改主页图标LOGO,在多媒体管理器中的wiki分类中上传你的logo.png即可 安装插件(http://yourdomain/path_to_dokuwiki/home?do=admin&page=extension),除了默认插件外,根据需要安装了常用的tag plugin ,Pagelist Plugin ,New PHP Markdown plugin ,Indexmenu Plugin ,可以参考蔡宗融的推荐 开始使用Dokuwiki: # 基本编辑语法(官方文档) 创建新页面(参考)

自动备份网站文件及数据库到dropbox

·508 字·2 分鐘
環境 # 第三方资源:Dropbox Uploader 系统环境:Ubuntu x64 操作步驟 # 在dropbox官方创建一个新的应用「 Dropbox API App」,获得APP key和APP secret 在终端上下载并执行本文开头所引用的第三方资源 1curl "https://raw.githubusercontent.com/andreafabrizi/Dropbox-Uploader/master/dropbox_uploader.sh" -o dropbox_uploader.sh 2sudo $chmod +x dropbox_uploader.sh 3sudo $./dropbox_uploader.sh 按照屏幕提示输入APP key和APP secret,许可权限类型选择a,确认后在浏览器中打开终端给出的token链接,完成验证