通常的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
<?phpclass 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";}}
如果你希望方法( 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
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 configuredif(!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 messageif(in_array($_SERVER['REMOTE_ADDR'], $blocked)){ throw new Api_Error('Spammer', 'Your IP address is blocked.');}}}
// 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.');
}
}