nexus-rest-api / nexus
Lightweight and fast PHP framework for building RESTful APIs.
Installs: 39
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 1
Forks: 0
Open Issues: 0
Type:framework
Requires
- php: ^7.4 || ^8.0
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
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
<?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