iamdev / rest-in-peace
1.0.0
2024-01-17 02:23 UTC
Requires
- php: ^7.4 || ^8.0
This package is not auto-updated.
Last update: 2024-09-26 04:13:30 UTC
README
一种简单的方法,在PHP项目中提供REST API。遵循https://www.restapitutorial.com/lessons/restquicktips.html的一般指南。
有多简单?
嗯,
use iamdev\rest\Rest;
Rest::inPeace(
[
'users' => new Users(),
'songs' => new Songs(),
'playlists' => new Playlists(),
],
);
此代码将通过简单地实现Restifier来处理如/users/1/songs
或/users/3/playlists/2/songs
这样的路由
use iamdev\rest\Context;
use iamdev\rest\Restifier;
class Playlists implements Restifier
{
public function list(Context $context): ?array
{
//return a list ;
}
public function create(object $resource, Context $context): string
{
//create a $resource
//return the new id;
}
public function retrieve($id, Context $context): object
{
// return a resource with id $id
}
public function update($id, $resource, Context $context)
{
// update the $resource
}
public function delete($id, Context $context)
{
// delete $id
}
}
查看这个app以获取更完整的实现
安装
php composer.phar require "iamdev/rest"
处理嵌套路由
GET /users/3/playlists/2/songs
将按顺序调用
- Users.php#retrieve(3)
- Playlists.php#retrieve(2)
- Songs.php#list()
假设你正在使用延迟加载并且不想调用数据库3次,你可以利用Context
- isLeaf表示restifier是否位于路由的末尾,因此,在Users.php的示例中,它将是false,在Songs.php中将是true
- resourceMap表示路由的不同部分,在这种情况下,它将包含
array(3) { ["users"]=> "3" ["playlists"]=> "2" ["songs"]=> NULL }
选项
Rest::inPeace的参数为(array $routes, $path = null, array $ioHandlers = [])
$path
默认情况下,路径解析为parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)
,如果这对你不起作用,请使用此参数。
$ioHandlers
是一个实现IOHandler的对象数组。默认情况下,有两个用于json和XML的实现。如果您需要替换它或添加新格式,请使用此参数。
查看使用此选项的示例
注意
为了使用默认的路由策略,您需要重新编写您的URL,例如对于Apache
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^api(.*)$ with_options.php [L,QSA]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ simple.php [L,QSA]
如果不这样做,您的路由将需要像index.php/users/1
这样的形式,并且在调用Rest::inPeace之前必须删除index.php
异常
只需抛出这些异常来处理HTTP状态响应