nexus-rest-api/nexus
Composer 安装命令:
composer require nexus-rest-api/nexus
包简介
Lightweight and fast PHP framework for building RESTful APIs.
关键字:
README 文档
README
Nexus php is a lightweight and fast PHP framework for building RESTful APIs.
Installation
Easy installation via Composer:
composer require nexus-rest-api/nexus
Getting started
APP
Nexus rest api uses an app decorator to handle all the functionality. There is also a possibility to pass config to the app while creating it. The order of values in config does not matter but the key names do.
<?php use Nexus\App; $config = [ 'prefix' => 'api', 'db_connection' => [ 'host' => 'localhost', 'user' => 'root', 'password' => '', 'database' => 'nexus' 'port' => 3306 // optional (default 3306) ], 'CORS' =>[ 'allowedOrigins' => ['http://localhost', 'https://*.example.com'], 'allowedHeaders' => ['x-allowed-header', 'x-other-allowed-header'], 'allowedMethods' => ['DELETE', 'GET', 'POST', 'PUT'], 'exposedHeaders' => ['Content-Encoding'], 'maxAge' => 0 ] ] $app = new App($config);
ENVIRONMENTS
The framework allows for two different environments namely development and production. The difference being that in development if there is an error the stacktrace will be shown in the response. environment is part of the config of the app. By default development is set as the env.
<?php $config =[ "ENV" => "production" ]
HTACCESS
A .htaccess file is required for the router to work.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php/$1 [L]
SERVING THE APP
If your using composer the following script in the composer.json file will launch the app on port 9000 when typing the command composer start in the terminal.
"scripts": { "start": [ "Composer\\Config::disableProcessTimeout", "php -S localhost:9000 -t ./" ] }
ROUTER AND REQUESTS
All request are handled by the router, the requests use a string as name and a callback for the logic of the request. The router returns the data in json format. The order and format of the parameters in the request is not important. The following requests are supported in this framework:
- GET
- POST
- PUT
- DELETE
examples:
<?php // Get request $app->get('/ping', function(Request $request) { return [ 'code' => 'OK', 'message' => 'pong' ]; }); // Post request $app->post('/blog', function(Request $request) { return $request->body(); }); // Put request $app->put('/blog/:id', function(Request $request) { $param = $request->params()['id']; // do something with $param }); // Delete request $app->delete('/blog/:id', function(Request $request) { $param = $request->params()['id']; // do something with $param });
Important request object parameters
| Parameter | code example | info |
|---|---|---|
| totalRequestTime | $request->totalRequestTime |
returns in milliseconds how long the request took to complete |
| requestUri | $request->requestUri |
returns the uri of the request |
| requestMethod | $request->requestMethod |
returns the http method used in the request |
| httpAuthorization | $request->httpAuthorization |
returns the bearer token given with the request |
| params | $request->params() |
returns the params of the request |
| body | $request->body() |
returns the body of the request |
ROUTER GROUPS
The router can group routes together and set a prefix for all routes in that group. Note nesting groups is not supported yet.
example:
- request /api/health/ping
- request /api/health/status
<?php $app->group(['prefix' => '/health'], $app->get('/ping', function(Request $request) { return [ 'code' => 'OK', 'message' => 'pong' ]; }) ,$app->get('/status', function(Request $request) { return [ 'code' => 'OK', 'message' => 'pong' ]; }) );
MIDDLEWARE
Middleware is an extra function passed on to a request that is executed before the request is handled. The middleware can also stop a route from being executed, this by not calling the $next() function.
example:
<?php $middleware = function(Request $request, Closure $next) { echo "this is a middleware function"; $next(); }; // The order of the parameters is not important $app->get('/ping', $middleware, function(Request $request) { return [ 'code' => 'OK', 'message' => 'pong' ]; });
DATABASE CONNECTION
in the config of the app, you can configure the database for the app to use. The app allows you to open and close the connection on demand with the functions dbConnect() and dbDisconnect(). The example below uses a prepared statement to combat sql injections. A normal statement can also be used.
<?php $findUser = function(App $app, String $id){ $app::dbConnect(); // Opens the connection with the database // Prepared statement $statement = $app()::db()->prepare( 'SELECT * FROM user WHERE id = ?' ); $statement->bind_param('ss', $id); $statement->execute(); $result = $statement->get_result()->fetch_all(MYSQLI_ASSOC); $app::dbExit(); // Closes the connection with te database return $result; };
MODULES
If you want to add extra functionality to the app eg. a logger. This can be done use the append module method. This takes a key (string) and a value (object or closure).
// Appending the module $app::appendModule('logger', new Logger()); // Accessing the appended module $logger = $app:requireModule('logger'); $logger::logAction('...');
ERROR HANDLING
The router has build in error handling, this framework comes with some exceptions that can be thrown throughout the application. These exceptions will be caught by the router and an error message wil be send to the end user.
Different exceptions
| HTTP status code | Name | Exception |
|---|---|---|
| 400 | Bad Request | throw new BadRequestException(String) |
| 401 | Unauthorized | throw new UnauthorizedException(String) |
| 403 | Forbidden | throw new ForbiddenException(String) |
| 404 | Not Found | Handled by the router |
| 413 | Payload Too Large | throw new PayloadTooLargeException(String) |
| 429 | Too Many Requests | throw new TooManyRequestsException(String) |
| 500 | Internal Server Error | Fallback for exceptions not in this list and other errors |
| 501 | Not Implemented | throw new NotImplementedException(String) |
| 502 | Bad Gateway | throw new BadGatewayException(String) |
<?php // Use case $app->get("/users", function(Request $request) { if(!validateToken($request->httpAuthorization)) throw new UnauthorizedException("User is not logged in"); });
OPTIMIZING THE APP
Once done with developing you app. You can add this script and config option to you composer.json file to optimize the composer autoloader. Note using the build command during development can cause issues!
"scripts": { "start": [ "Composer\\Config::disableProcessTimeout", "php -S localhost:9000 -t ./" ], "build": [ "composer update --optimize-autoloader", "composer dump-autoload --optimize" ] }, "config": { "optimize-autoloader": true }
Suggested packages to use with this framework
- firebase/php-jwt
- symfony/dotenv
- ramsey/uuid
nexus-rest-api/nexus 适用场景与选型建议
nexus-rest-api/nexus 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 41 次下载、GitHub Stars 达 0, 最近一次更新时间为 2022 年 06 月 12 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「framework」 「php」 「rest」 「api」 「router」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 nexus-rest-api/nexus 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 nexus-rest-api/nexus 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 nexus-rest-api/nexus 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
PHP Framework HLEB2 is the foundation of the web application. Provides ease of development and application performance.
A PSR-7 compatible library for making CRUD API endpoints
Api bundle
Alfabank REST API integration
A Flickr wrapper to allow you to call the Flickr api with Guzzle as the backend.Goal is to have 100% Flickr api coverage rather than just upload/display photos (currently at 23%).
High-performance, opinionated PHP 8 web framework with O(1) routing, parallel async MySQL, type-safe asset bridge, and React-island frontend
统计信息
- 总下载量: 41
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 1
- 点击次数: 9
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2022-06-12