一个用于在PHP(以及javascript)中快速构建HTTP API的库

0.100 2020-04-16 13:58 UTC

This package is auto-updated.

Last update: 2024-09-16 23:41:04 UTC


README

QUAPI(Kwappy)是一个轻量级的库,用于快速构建HTTP API。它提供了基于操作参数值调用处理程序的方法,提供辅助方法以检查和检索GET/POST参数,发送成功/错误消息的方法,将注册处理程序类或对象转换为可序列化为JSON的数组的方法,以及用于处理客户端通信的javascript客户端。

示例

<?php


include(dirname(__FILE__).'/quapi/api.lib.php');
use QuickAPI as API;

/**
 * Some action that the API performs
 */
class Action1 implements API\APIHandler, 
{
    public function handleCall($args)
    {
        // Do something

        // Return a foo
        return new Foo();
    }
}


/**
 * Convert a foo object into a JSON-serializable array
 */
class FooConverter implements API\APIResultHandler
{
    public function prepareResult($res)
    {
        // Bars will be converted into arrays by the BarConverter later on :)
        return array('name' => $res->name, 'bars' => $res->getBars());
    }
}

/**
 * Convert a bar object into a JSON-serializable array
 */
class BarConverter implements API\APIResultHandler
{
    public function prepareResult($res)
    {
        return array('barID' => $res->BarID, 'colour' => $bar->getColour());
    }
}


/**
 * Create an API that looks for arguments in $_GET/$_POST and uses the "action" argument to specify which 
 * action handler to invoke
 */
$api = new API\API(\array_merge($_GET, $_POST), 'action');


/**
 * Add an action to be called if the action parameter is "action1" or if "param1" is set
 */
$a1 = new Action1();
$api->addOperation(false, array('param1'), $fi);
$api->addOperation('action1', array('param1'), $fi);


/**
 * Register converters to turn Foo objects and Bar objects in json-serializable arrays
 */
$api->registerResultHandler('Foo', new FooConverter());
$api->registerResultHandler('Bar', new BarConverter());

// Handle the request
$api->handle();

?>

您可以通过以下方式注册一个处理程序模块来检查提供者用户/密码参数:

$api->addAuth(new AuthHandler()); // $authHandler must implement APIAuth

通过以下方式获取javascript客户端:

<script>
<?php
include(dirname(__FILE__).'/quapi/api.lib.php');
use QuickAPI as API;
echo getAPIClient();
?>
</script>

或者通过将魔法参数apiGetClient传递给库脚本本身

<script src="http://path/to/api.php?apiGetClient"></script>