惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

酷 壳 – CoolShell
酷 壳 – CoolShell
H
Hacker News: Front Page
P
Palo Alto Networks Blog
T
ThreatConnect
Apple Machine Learning Research
Apple Machine Learning Research
博客园_首页
T
True Tiger Recordings
P
Privacy & Cybersecurity Law Blog
B
Blog
IT之家
IT之家
Last Week in AI
Last Week in AI
F
Full Disclosure
Hacker News: Ask HN
Hacker News: Ask HN
C
Comments on: Blog
Microsoft Azure Blog
Microsoft Azure Blog
C
Cybersecurity and Infrastructure Security Agency CISA
Microsoft Security Blog
Microsoft Security Blog
博客园 - 【当耐特】
N
News and Events Feed by Topic
NISL@THU
NISL@THU
腾讯CDC
雷峰网
雷峰网
Security Latest
Security Latest
李成银的技术随笔
M
Microsoft Research Blog - Microsoft Research
L
LangChain Blog
L
Lohrmann on Cybersecurity
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
C
Check Point Blog
Y
Y Combinator Blog
Recent Announcements
Recent Announcements
博客园 - Franky
N
News | PayPal Newsroom
V
V2EX
A
About on SuperTechFans
The Register - Security
The Register - Security
月光博客
月光博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google Online Security Blog
Google Online Security Blog
MyScale Blog
MyScale Blog
Cisco Talos Blog
Cisco Talos Blog
Vercel News
Vercel News
WordPress大学
WordPress大学
C
Cyber Attacks, Cyber Crime and Cyber Security
The Hacker News
The Hacker News
IntelliJ IDEA : IntelliJ IDEA – the Leading IDE for Professional Development in Java and Kotlin | The JetBrains Blog
IntelliJ IDEA : IntelliJ IDEA – the Leading IDE for Professional Development in Java and Kotlin | The JetBrains Blog
爱范儿
爱范儿
A
Arctic Wolf
L
LINUX DO - 最新话题
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More

博客园 - witer666

[android开发必备] Android开发者社区汇总 - witer666 android定时器 微博feed系统的push和pull模式和时间分区拉模式架构探讨 一个mysql小技巧 redhat安装memcacheQ - witer666 php empty问题 Linux PHP连接MSSQL Curl参数一览 Redhat Memcache UDF安装配置 Redhat Mongodb学习笔记 PHP使用技巧 位运算符C语言 - witer666 Redhat Lighttpd安装配置 HTTP 状态代码表示什么意思? PHP正则表达式学习参考的文章 Redhat Cacti安装配置 Percona-Server5.5安装配置 50点提高PHP编程效率 引入缓存提升性能 wget使用
PHP API 框架开发的学习
witer666 · 2013-07-28 · via 博客园 - witer666

基于互联网的应用正变得越来越普及,在这个过程中,有更多的站点将自身的资源开放给开发者来调用。对外提供的API 调用使得站点之间的内容关联性更强,同时这些开放的平台也为用户、开发者和中小网站带来了更大的价值。

在开发API前,你需要的是给API设定一个框架,这个框架一定是要简单的且是容易扩展的。下面就是用就来看看如何使用PHP来创建一个API。

API框架需要的特性

  • 面向对象和结构化的代码
  • 可修改的URL结构
  • 创建多个版本
  • 使用Hook来扩展框架API功能
  • API可连接数据库表
  • 可定义多种输出格式
  • 选择方法请求类型(GET, POST, PUT, DELETE)

API框架的组成部分

API Framework主要由下面三中类型元素组成:

  • Services
  • Hooks
  • Parsers

在一个运行的API中,每种类型的元素都有其自己的任务。下面就来详细说说每一种元素。

api-framework

通常的API请求URL如下:

http://www.domain.com/api/version/service/method/param_name/param_key.extension

Service

Service Class是API请求的控制器。这个Class包含了API可以使用的method,所以Service Class会需要计算和处理数据。

为了使method可以被请求,你需要将method设置为公开(public),并为service method设置请求类型(GET, POST, PUT, DELETE)。

下面是一个Service Class的类,你可以设置默认的请求方式为GET,并且version method可以接受GET和POST请求。

PHP

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

<?php

classMyApi_Service_HelloworldextendsApi_Service_IService{

publicfunction__construct($api){

parent::__construct($api);

// Set execute request methods

$this->addAllowedMethod("execute",Api_Request::METHOD_POST);

$this->addAllowedMethod("version",Api_Request::METHOD_POST);

$this->addAllowedMethod("version",Api_Request::METHOD_GET);

}

publicfunctionexecute($params,$config){

$this->code=200;

return"Hello world";

}

publicfunctionversion($params,$config){

$this->code=200;

return"Version 1.0";

}

}

这里是一个可以使用的使用的API请求类型:

  • Api_Request::METHOD_GET
  • Api_Request::METHOD_POST
  • Api_Request::METHOD_PUT
  • Api_Request::METHOD_DELETE

如果你希望方法( method)名以驼峰式命名的话,如:

public myNewHelloWorld{}

那么你就需要在你的url中使用”my-new-hello-world”来请求这个方法(/v1/helloworld/my-new-hello-world.xml)。

Hook

Hook是一个可以绑定特定行为的类。哪些Hooks 会在执行力中执行特定的点(如图所示)。它可以让你在服务使用前修改数据。下面是一些可能的hook示例:

  • 监测用户使用的API key是否在数据库中存在。
  • 监测特定的IP地址是否是允许使用服务或行为的。
  • 在文件或者数据库中记录用户的请求日志。
  • 禁止特定的 IP使用API。
  • 限制IP每小时对API的请求数。

上面的只是一些示例,你可以发挥你的想象任意的添加Hook。下面是一个关于Hook的实例:

PHP

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

classApi_Hook_BlockIpextendsApi_Hook_IHook{

publicfunctionexecute(){

// Current called service

$service=func_get_arg(0);

// Get config array

$config=$this->api->getConfig();

// Stop if blocks is not configured

if(!isset($config['block']))return;

// Convert comma separated list to array

$blocked=explode(',',$config['block']);

// Check if the user IP is blocked

// If blocked show him a message

if(in_array($_SERVER['REMOTE_ADDR'],$blocked)){

thrownewApi_Error('Spammer','Your IP address is blocked.');

}

}

}

为了使上面的Hook可以正常的工作,你需要在config文件中添加这样一行:

block = ip1,ip2,ip3

接下来就是讲解不同种类的hook了:

  • HOOK_CONFIG_LOADED: 这个hook是在加载了配置(config)请求的。他可以用来修改或添加一些配置信息
  • HOOK_BEFORE_SERVICE_EXECUTE: 这个hook是在服务执行前执行的,所以它可以用来校核用户身份,查看是否有具体的权限。
  • HOOK_MODIFY_PARSER: 使用这个Hook可以在输出数据解析前修改解析器。

如果要启用钩子则需要到程序的入口(endpoint.php)进行修改。

Parsers

解析器用来转化数据到特定的输出格式的。例如是XML,机械器就是用定义的APi请求文件扩展名来表示。例如:

  • /v1/helloworld.xml: 则使用Xml.php作为解析器
  • /v1/helloworld.json: 则使用Json.php作为解析器

你可以根据自己的需求定义标准的解析器,如:

  • XML
  • CSV
  • JSON
  • Printr
  • TXT

下面是一种类似PHP中print_r的输出格式示例:

PHP

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

classApi_Parser_PrintrextendsApi_Parser_IParser{

/**

* Content type

* @var string

*/

public$content_type="text/plain";

/**

* Parse to XML

*

* @return string

*/

publicfunctionparse(){

returnprint_r($this->_data,true);

}

}

框架会根据命名规则自动寻找适合的输出格式。

要顺利的开发一个PHP API,除了以上的这些还需要做的有:

  1. 创建一个基本的API配置文件,并修改好程序的入口。
  2. 配置自己想要的REST URL结构。
  3. 记录接口中产生的错误。~