aria-php / aria-rest
可扩展的微服务REST框架
Requires
- php: >=7.0
- symfony/event-dispatcher: ^5.0
- symfony/http-foundation: ^5.0
- symfony/routing: ^5.0
Requires (Dev)
- guzzlehttp/guzzle: ^6.5
- phpunit/phpunit: ^8.1
- squizlabs/php_codesniffer: ^3.4
README
此库提供了一种(希望是)简单的方式来定义API。它支持多种HTTP方法和版本控制。
安装
将存储库添加到您的composer.json文件中
"repositories": [
{
"type": "vcs",
"url": "https://gitlab.com/aria-php/aria-rest.git"
}
],
然后从您的项目中运行composer require aria-php/aria-rest
。
用法
总的来说,它是一个高度简化的Symfony路由包装器,特别是修改为提供非常简单的方式来公开基于页面的HTTP方法。
您首先在端点页面上公开单个HTTP方法(GET / POST / 等),然后将此端点页添加到APIDefinition集合中。此集合可以向一组特定的API端点添加可选的前缀 - 通常这将用于支持版本控制,以及/或将特定子模块的API命名空间到合适的位置。
您可以通过查看example/index.php
来找到一个定义API端点并为其分配不同HTTP方法以支持的工作示例。
设置您的端点
为了让库工作,您需要做一些事情(对于ARIA来说,这些事情已经完成了,但请检查)。
- 首先,您需要修改您的 .htaccess 文件,使其指向一个包含API路由调用(请参阅example/index.php)的PHP文件的url。
<IfModule mod_rewrite.c>
RewriteEngine on
#RewriteBase /
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond $1 !^(index\.php)
RewriteRule ^(.*)$ /index.php/$1 [L]
</IfModule>
- 这个路由运行器基本上包含
// Serve the routes
$router = router::router();
$router->serve();
创建您的API端点
- 首先,通过创建一个实现了HTTP请求方法之一(例如
GETEndpoint
或POSTEndpoint
)的类来创建您的端点。这些方法应返回一个值,该值可以是简单类型或实现JsonSerializable的对象,该对象将被API请求返回。
class MyEndpoint implements GETEndpoint {
public function GET(array $args = []) {
return [
'foo' => 'bar'
];
}
}
- 接下来,将端点添加到API定义中。API定义是一组端点的集合,这些端点挂载在特定的版本化端点上。
$definition = new APIDefinition('namespace'); $definition->addRoute('myapi/myendpoint/', MyEndpoint::class);
You can optionally specify a version for this endpoint:
$definition = new APIDefinition('namespace', 'v1'); $definition->addRoute('myapi/myendpoint/', MyEndpoint::class);
* Finally, publish your API to the central router object
$router = router::router();
$router->addAPI($definition);
## Handling variables
Within your page handler VERB endpoint, you have two possible ways of getting variables.
The first is the `$args` line which contains variables extracted from the url line as defined by your route handler. The second is to get GET/POST/PUT/PATCH variables using the `->request()` method.
e.g.
class MyEndpoint implements GETEndpoint {
public function GET(array $args = []) {
return [
'foo' => $this->request('bar') // Return the contents of ?bar= from the GET line
];
}
}