1. Go to this page and download the library: Download haszi/router 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/ */
haszi / router example snippets
use Haszi\Router\Router;
use Haszi\Router\Dispatcher;
$router = new Router();
$router->addRoute('*', '/greet', function () { echo 'Hello World!'; });
$router->get('/users', 'Users@list');
$dispatcher = new Dispatcher($router);
$dispatcher->dispatch('GET', '/greet);
// Closures
$router->get('/ping', fn () => 'pong');
$router->get('/sum/{firstNum}/{secondNum}', function ($first, $second) {
return $first + $second;
});
// Using the controller@method notation
$router->get('/users', 'Users@list');
$router->get('/login', 'Login@login');
// 'id' which can be one ore more of any of characters
// will be passed to Users::update() / Users->update()
$router->put('/users/{id}', 'Users@update');
// 'id' which will be one or more digits
// will be passed to Users::update() / Users->update()
$router->get('/artist/(\d+)', 'Users@update');
// will match /albums/2023 or /albums/acdc or /albums
$router->get('/albums/{year}?', $handler);
// will match /albums/2023 or /albums
$router->get('/albums(/d+)?', $handler);
$router->group('/users/{id}', function ($router) use ($id) {
$router->get('/posts', 'Users@getPosts');
$router->get('/comments', 'Users@getComments');
});
// is equivalent to
$router->get('/users/{id}/posts', 'Users@getPosts');
$router->get('/users/{id}/comments', 'Users@getComments');
$this->router->setRouteNotFoundHandler(fn () => 'Route not found');
// returns 'Route not found'
$this->router->getRouteNotFoundHandler();