composer require amranich/ajax-router
You can copy/paste this code snippet for a quick start.
We're using Guzzle PSR-7 interface implementation here, but you can use any other library you like as long as it implements the same interface.
?php
require __DIR__ . '/vendor/autoload.php';
use AmraniCh\AjaxRouter\Dispatcher;
use AmraniCh\AjaxRouter\Route;
use AmraniCh\AjaxRouter\Psr7\PSR7ResponseSender;
use AmraniCh\AjaxRouter\Router;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Psr7\ServerRequest;
try {
$request = ServerRequest::fromGlobals();
$router = new Router($request, 'route', [
// ?route=hello&name=john
Route::get('hello', function ($params) {
$response = new Response;
$response->getBody()->write("hello master " . $params["name"]);
return $response;
}),
]);
$dispatcher = new Dispatcher($router);
$dispatcher->dispatch();
} catch (Exception $ex) {
$response = new Response(
$ex->getCode() ?: 500,
['Content-type' => 'application/json'],
json_encode(['message' => $ex->getMessage()])
);
$sender = new PSR7ResponseSender($response);
$sender->send();
exit();
}
If you like to put the business logic in a separate class or in a controller, you can route your requests to them like this :
Route::get('getProfile', [UserManager::class, 'getProfile']),
Or :
Route::get('getProfile', 'UserManager@getProfile')
But you have after to register the controller namespace/instance in the router, like this :
$router->registerControllers([
UserManager::class,
]);
If the controller/class has some dependencies that must be passed within the constructor, you can still instantiate the controller on yourself :
$router->registerControllers([
new UserManager($dependencyOne, $dependencyTwo)
]);
I want to catch exceptions that only occurs from my routes actions, and not those thrown by the library or somewhere else, how I can do that ?
Answer :
$dispatcher->onException(function (\Exception $ex) {
// $ex exception thrown by a route action
});
The idea of the library came to my mind a long time ago when I was mostly developing web applications using just plain PHP, some of these applications were performing a lot of AJAX requests into a single PHP file, that file can have a hundred lines of code that process these requests depending on a function/method name that send along with the request, so I started to think of ways to clean up this file to improve the readability and maintainability of the code.
A special thanks to JetBrains company for their support to my OSS contributions.
The library is licensed under the open source MIT licence.