PHP code example of corviz / router

1. Go to this page and download the library: Download corviz/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/ */

    

corviz / router example snippets


use Corviz\Router\Facade\RouterFacade as Router;

/*
 * Application routes
 */
Router::get('/', function() {
    return 'Hello world!';
});

Route::get('/user/(\d+)', function(int $id){
    return "Show information for user $id";
});

echo Router::dispatch();
!Router::found() && http_response_code(404);

namespace MyApplication;

class UserController 
{
    public function show(int $id)
    {
        //Search for user information in the database
        //...
        
        return $user;
    }
}

Router::get('/user/(\d+)', [\MyApplication\User::class, 'show']);

use Corviz\Router\Facade\RouterFacade as Router;

Router::get('/user/(\d+)', function(int $id) { /*...*/ });
Router::post('/user/new', function() { /*...*/ });
Router::delete('/user/(\d+)', function(int $id) { /*...*/ });

use Corviz\Router\Middleware;

class AcceptJsonMiddleware extends Middleware
{
    public function handle(Closure $next): mixed
    {
        //Interrupts in case wrong content-type was sent
        if (!$_SERVER['CONTENT_TYPE'] != 'application/json') {
            return 'Invalid content type';
        }
        
        return $next(); //Proceed with the request
    }
}

use Corviz\Router\Facade\RouterFacade as Router;

Router::any( /*...*/ )
    ->middleware(AcceptJsonMiddleware::class);

use Corviz\Router\Facade\RouterFacade as Router;

Router::any( /*...*/ )
    ->middleware([Middleware1::class, Middleware2::class]);

use Corviz\Router\Facade\RouterFacade as Router;

Router::prefix('user')->group(function() {
    Router::get('list', function() { /**/ });    
    Router::get('(\d+)', function(int $id) { /**/ });    
    Router::post('new', function() { /**/ });    
    Router::patch('(\d+)/update', function(int $id) { /**/ });    
    Router::delete('(\d+)/delete', function(int $id) { /**/ });    
});

use Corviz\Router\Facade\RouterFacade as Router;

Router::prefix('api')
    ->middleware(CheckTokenMiddleware::class)
    ->middleware(AcceptJsonMiddleware::class)
    ->group(function() { /* ... */ });

$method = 'GET'; //or POST, PUT, PATCH, DELETE...
$path = 'users/1/show';

$output = Router::dispatch($method, $path);

use Corviz\Router\Dispatcher;

$router = new Dispatcher();
$router2 = new Dispatcher();
$router3 = new Dispatcher();
//so on...

$router1->get('route1', /* ... */);
$router1->prefix('group1')->group(function() use (&$router1){
    $router1->get('route2', /* ... */);
    $router1->get('route3', /* ... */);
});

echo $router1->dispatch();
!$router1->found() && http_response_code(404);