PHP code example of haszi / router

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);

$router->get('/route', $handler);
$router->head('/route', $handler);
$router->post('/route', $handler);
$router->put('/route', $handler);
$router->delete('/route', $handler);
$router->patch('/route', $handler);
$router->options('/route', $handler);

$router->any('/route', $handler);

$router->addRoute(['GET','HEAD'], '/route', $handler);

// 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();

$router->before('GET', '/hello-world', fn () => 'Hello ');
$router->before('GET', '/hello-world', fn () => 'World!');

$beforeRoute = $router->getBeforeMiddleware('GET', 'hello-world');

$result = '';
foreach ($beforeRoute as $middleware) {
    $result .= ($middleware['route']->getHandler())();
}
// $result contains 'Hello World!'

$dispatcher = new Dispatcher($router);

$dispatcher->dispatch('GET', '/about-us);