1. Go to this page and download the library: Download denosyscore/routing library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
denosyscore / routing example snippets
// Create a new router instance
$router = new Denosys\Routing\Router();
// Define a route
$router->get('/', function (): ResponseInterface {
$response = new Laminas\Diactoros\Response();
$response->getBody()->write('Hello, World!');
return $response;
});
// Create Request
$request = Laminas\Diactoros\ServerRequestFactory::fromGlobals();
// Dispatch the request
$response = $router->dispatch($request);
// Output the response
echo $response->getBody();
// Global middleware runs on ALL routes
$router->use(LoggingMiddleware::class);
$router->use(CorsMiddleware::class);
// Supports arrays
$router->use([ErrorHandlerMiddleware::class, SessionMiddleware::class]);
// Routes defined before or after - doesn't matter
$router->get('/users', 'UserController@index');
$router->get('/posts', 'PostController@index');
// Single middleware
$router->get('/admin', 'AdminController@index')
->middleware('auth');
// Multiple middleware
$router->get('/api/users', 'UserController@index')
->middleware(['auth', 'throttle']);
// Chained middleware (applies to next route only)
$router->middleware('auth')
->get('/dashboard', 'DashboardController@index');
// Register aliases
$router->aliasMiddleware('auth', AuthMiddleware::class);
$router->aliasMiddleware('throttle', ThrottleMiddleware::class);
// Register groups (can reference aliases or other groups)
$router->middlewareGroup('web', ['session', 'csrf', 'cookies']);
$router->middlewareGroup('api', ['throttle', 'auth']);
// Use aliases/groups on routes
$router->get('/dashboard', 'DashboardController@index')
->middleware('web');
$router->get('/api/users', 'UserController@index')
->middleware('api');
// Modify existing groups
$router->prependMiddlewareToGroup('web', 'logging');
$router->appendMiddlewareToGroup('api', 'cors');
$router->middleware('auth')->group('/admin', function ($group) {
$group->get('/dashboard', 'AdminController@dashboard');
$group->get('/users', 'AdminController@users');
});
// Exclude from route middleware
$router->get('/test', 'TestController@index')
->middleware(['auth', 'logging', 'throttle'])
->withoutMiddleware('logging');
// Exclude inherited group middleware
$router->middleware(['auth', 'admin'])->group('/admin', function ($group) {
$group->get('/dashboard', 'AdminController@dashboard'); // Has auth + admin
$group->get('/public', 'AdminController@public')
->withoutMiddleware('auth'); // Only has admin
});
// Exclude multiple middleware
$route->withoutMiddleware(['logging', 'throttle']);