基于互联网的应用正变得越来越普及,在这个过程中,有更多的站点将自身的资源开放给开发者来调用。对外提供的API 调用使得站点之间的内容关联性更强,同时这些开放的平台也为用户、开发者和中小网站带来了更大的价值。 在开发API前,你需要的是给API设定一个框架,这个框架一定是要简单的且是容易扩展的。下面就是用就来看看如何使用PHP来创建一个API。 API框架需要的特性
API框架的组成部分 API Framework主要由下面三中类型元素组成:
在一个运行的API中,每种类型的元素都有其自己的任务。下面就来详细说说每一种元素。 通常的API请求URL如下: http://www./api/version/service/method/param_name/param_key.extension ServiceService Class是API请求的控制器。这个Class包含了API可以使用的method,所以Service Class会需要计算和处理数据。 为了使method可以被请求,你需要将method设置为公开(public),并为service method设置请求类型(GET, POST, PUT, DELETE)。 下面是一个Service Class的类,你可以设置默认的请求方式为GET,并且version method可以接受GET和POST请求。 <?php class MyApi_Service_Helloworld extends Api_Service_IService{ public function __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); } public function execute($params, $config){ $this->code = 200; return "Hello world"; } public function version($params, $config){ $this->code = 200; return "Version 1.0"; } } 这里是一个可以使用的使用的API请求类型:
如果你希望方法( method)名以驼峰式命名的话,如: public myNewHelloWorld{} 那么你就需要在你的url中使用”my-new-hello-world”来请求这个方法(/v1/helloworld/my-new-hello-world.xml)。 Hook Hook是一个可以绑定特定行为的类。哪些Hooks 会在执行力中执行特定的点(如图所示)。它可以让你在服务使用前修改数据。下面是一些可能的hook示例:
上面的只是一些示例,你可以发挥你的想象任意的添加Hook。下面是一个关于Hook的实例: class Api_Hook_BlockIp extends Api_Hook_IHook { public function execute(){ // 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)){ throw new Api_Error('Spammer', 'Your IP address is blocked.'); } } } 为了使上面的Hook可以正常的工作,你需要在config文件中添加这样一行: block = ip1,ip2,ip3 接下来就是讲解不同种类的hook了:
如果要启用钩子则需要到程序的入口(endpoint.php)进行修改。 Parsers解析器用来转化数据到特定的输出格式的。例如是XML,机械器就是用定义的APi请求文件扩展名来表示。例如:
你可以根据自己的需求定义标准的解析器,如:
下面是一种类似PHP中print_r的输出格式示例: class Api_Parser_Printr extends Api_Parser_IParser{ /** * Content type * @var string */ public $content_type = "text/plain"; /** * Parse to XML * * @return string */ public function parse(){ return print_r($this->_data, true); } } 框架会根据命名规则自动寻找适合的输出格式。 要顺利的开发一个PHP API,除了以上的这些还需要做的有:
Related posts: |
|