hrishikesh214 / php-api
帮助您在PHP中轻松构建RESTful API
v1.7
2021-02-28 05:49 UTC
README
在PHP中轻松创建RESTFull API
It supports only JSON but you can change output :-)
索引
安装
composer require hrishikesh214/php-api
然后在您的文件中
require 'vendor/autoload.php';
配置
在深入了解 PHPAPI
之前,我们需要做一些配置
在您的根目录下创建 .htaccess
文件并粘贴以下代码
RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php?URL=$1 [L]
文档
创建客户端
$client = new phpapi\Client();
您也可以传递 基本地址
$client = new phpapi\Client("api/");
所有子端点都将通过 api/
访问
运行客户端
print_r($client->run(isset($_GET['URL']) ? $_GET['URL'] : ""));
此 $client->run()
返回响应字符串,因此您可以将它存储在变量中进行进一步处理或直接将其作为响应打印出来
创建端点
$client->mount('GET', 'token', function(){ //some calculations return $token; });
仅允许某些请求方法: 'PUT', 'POST', 'DELETE', 'PATCH', 'GET', 'PURGE'
mount
返回一个布尔值,表示端点是否成功挂载
传递URL参数
Client
将自动将URL参数传递给响应函数
以下是一个示例
$client->mount('GET', 'wish/:name/:age', function($props){ return "Hi $props['name'], you are $props['age] years old!"; });
URI参数将直接以关联数组的形式传递给响应函数,根据传递的参数键进行传递
所有其他 posted
参数将自动存储在 $_POST
中
注意
如果在挂载时定义了参数但没有传递,则将其赋予空值
POST端点
$respond = function(){ return $_POST; //It will have all posted data! }; $client->mount("POST", 'checkpost', $respond);
追踪整个API
您可以使用一个函数来追踪具有所有挂载端点的详细配置的整个API客户端
$client->trace(true|false);
如果以上值为true,则最终API结果也将包括API配置
这还包括请求的配置
示例输出:
{ "track": { "routes": { "POST": { "api/wish": { "base": "api/wish", "type": "POST", "params": [ ] }, "name": { "base": "name", "type": "POST", "params": [ ] } }, "GET": { "api/msg": { "base": "api/msg", "type": "GET", "params": [ ] }, "api/wish": { "base": "api/wish", "type": "GET", "params": { "name": 3 } }, "name": { "base": "name", "type": "GET", "params": { "name": 3 } }, "/": { "base": "/", "type": "GET", "params": [ ] } } }, "base": "", "request_blocks": [ "api", "msg" ], "request_uri": "api/msg", "request_type": "GET" }, "result": "trial" }
在上面的示例中,结果将包含来自API的结果
设置请求错误
存在一个默认的错误处理器,但您可以更改它!
404
$client->set404([ 'error_type' => 404, 'error_msg' => "Not Found" ]);
405
$client->set405([ 'error_type' => 405, 'error_msg' => "Method Not Allowed" ]);
外部路由
从外部文件导入路由
您也可以在外部文件中定义路由,您只需要使用 Helper
类。
例如(文件夹结构):
| myRoutes
| - api.php
| vendor (composer files)
| index.php
//index.php $client = new phpapi\Client(); $helper = new phpapi\Helper($client); $helper->use('myRoutes/api.php' [, basename: 'api']);
// myRoutes/api.php // You can define functions and also pass to callback $myFunc = function($props){ return "Good morning {$props['name']}"; }; $routes = [ [ "match" => 'msg', "type" => "get", "callback" => function(){ return "trial"; } ], [ "match" => 'wish/:name', "type" => "get", "callback" => $myFunc ], [ "match" => 'wish', "type" => "post", "callback" => function(){ return "Good morning {$_POST['name']}"; } ] ]; $config = [ 'base' => 'api' ];
在上面的代码中,$config['base']
将作为此文件中所有路由的基础。
$routes
将包含所有路由。
请保持格式,否则代码将无法工作!