theodorejb / phaster
快速 RESTful API 库
v2.9.0
2024-09-10 20:12 UTC
Requires
- php: >=7.4
- ext-json: *
- psr/http-message: ^1.1 || ^2.0
- shrikeh/teapot: ^2.3.1
- theodorejb/peachy-sql: ^6.1
Requires (Dev)
- phpunit/phpunit: ^9.6
- psalm/plugin-phpunit: ^0.19
- vimeo/psalm: ^5.26
README
Phaster 是一个用于轻松创建 RESTful API 端点的库。它与 Slim 框架配合良好,支持 PHP 7.4+。
安装
composer require theodorejb/phaster
用法
创建一个扩展 theodorejb\Phaster\Entities 的类并实现 getMap() 方法。默认情况下,表名将从类名推断,并且将选择此表中的所有映射列。
要连接其他表并修改输出值,实现 getBaseQuery() 和 getPropMap() 方法。将路由处理函数返回的可调用对象传递给您的 Slim 或其他 PSR-7 兼容框架。
<?php use theodorejb\Phaster\{Entities, Prop, QueryOptions}; class Users extends Entities { protected function getMap(): array { // map properties to columns in Users table return [ 'username' => 'uname', 'firstName' => 'fname', 'lastName' => 'lname', 'isDisabled' => 'disabled', 'role' => [ 'id' => 'role_id', ], ]; } protected function getSelectProps(): array { // map additional properties for selecting/filtering and set output options return [ new Prop('id', col: 'u.user_id'), new Prop('isDisabled', col: 'u.disabled', type: 'bool'), new Prop('role.id', col: 'u.role_id'), new Prop('role.name', col: 'r.role_name'), ]; } protected function getBaseQuery(QueryOptions $options): string { return "SELECT {$options->getColumns()} FROM Users u INNER JOIN Roles r ON r.role_id = u.role_id"; } protected function getDefaultSort(): array { return ['username' => 'asc']; } }
如果需要在基本查询中绑定参数,请使用 getBaseSelect。
use PeachySQL\QueryBuilder\SqlParams; // ... protected function getBaseSelect(QueryOptions $options): SqlParams { $sql = "WITH num_orders AS ( SELECT user_id, COUNT(*) as orders FROM Orders WHERE category_id = ? GROUP BY user_id ) SELECT {$options->getColumns()} FROM Users u INNER JOIN num_orders n ON n.user_id = u.user_id"; return new SqlParams($sql, [321]); } // ...
<?php use My\DatabaseFactory; use theodorejb\Phaster\{Entities, EntitiesFactory}; class MyEntitiesFactory implements EntitiesFactory { public function createEntities($class): Entities { return new $class(DatabaseFactory::getDb()); } }
<?php use theodorejb\Phaster\RouteHandler; $phaster = new RouteHandler(new MyEntitiesFactory()); $app->get('/users', $phaster->search(Users::class)); $app->get('/users/{id}', $phaster->getById(Users::class)); $app->post('/users', $phaster->insert(Users::class)); $app->put('/users/{id}', $phaster->update(Users::class)); $app->patch('/users/{id}', $phaster->patch(Users::class)); $app->delete('/users/{id}', $phaster->delete(Users::class));
示例 API 请求/响应
GET https://example.com/api/users?q[firstName]=Ted&q[isDisabled]=0&fields=id,username,role
{
"offset": 0,
"limit": 25,
"lastPage": true,
"data": [
{
"id": 5,
"username": "Teddy01",
"role": {
"id": 1,
"name": "Admin"
}
},
{
"id": 38,
"username": "only_tj",
"role": {
"id": 2,
"name": "Standard"
}
}
]
}
作者
Theodore Brown
https://theodorejb.me
许可证
MIT