usox / sharesta
使用严格的黑客方式创建 restful json api
v3.5.0
2020-05-15 05:59 UTC
Requires
- hhvm: ^4.1
- hhvm/hsl: ^4.1
- hhvm/hsl-experimental: ^4.50
- hhvm/type-assert: ^3
Requires (Dev)
- hhvm/hhast: ^4.1
- usox/hackmock: ^1
README
一个用于构建简单且易于使用的类似 rest api 的小型框架 - 使用严格的 Hack 语言编写(Hack)。
使用方法
首先,构建一些包含您逻辑的类...
final class HomeRoute implements \JsonSerializable { public function jsonSerialize(): string { return 'Welcome home'; } } final class UpdateUserRoute implements \JsonSerializable { public function __construct( private int $user_id, private \Usox\Sharesta\RequestInterface $request ): void { } public function jsonSerialize(): bool { // do some magic, e.g. access the request body by $this->request return true; } }
现在创建一个包含您的路由配置的类。
final class Routes implements Usox\Sharesta\RoutesInterface { public function registerRoutes(Usox\Sharesta\RouterInterface $router): void { $router->get( '/', (Usox\Sharesta\RequestInterface $request): \JsonSerializable ==> { return new HomeRoute(); } ); /** * Get variables from the path (e.g. `http://some.tld/users/123`) */ $router->post( '/users/:id', (Usox\Sharesta\RequestInterface $request): \JsonSerializable ==> { return new UpdateUserRoute( $request->getUriValues('id'), $request->getRequestBody() ); } ); } }
设置 sharesta,注册您的路由,让应用程序控制器处理您的请求。
<?hh // strict require_once 'vendor/autoload.php'; <<__Entrypoint>> function main(): noreturn { /* HH_IGNORE_ERROR[2050] */ $get_vars = dict($_GET); /* HH_IGNORE_ERROR[2050] */ $server_vars = dict($_SERVER); $factory = new Usox\Sharesta\ApiFactory(); $router = $factory->createRouter( $server_vars, $get_vars ); $routes = new Routes(); $routes->registerRoutes($router); $router->route( '' // path to the file. Leave it empty if your server configuration defaults to index.hh ); die(0); }
示例
查看 example/webroot/index.hh
以获取示例。