PHP code example of mrf0o / php-router

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

    

mrf0o / php-router example snippets




rfoo\PHPRouter\Router;

Router::get('/', function() {
    echo 'Hello World!';
});

Router::run();

use Mrfoo\PHPRouter\Router;

Router::get('/hello', function () {
    echo  '<h1>hello there</h1>';
});

Router::run();

Router::get('/hello/{name}', function ($name) {
    echo  '<h1>hello '.$name.'</h1>';
});

Router::get('/user/{name}', function ($name) {
    // ...
})->where('name', '[A-Za-z]+');

Router::get('/user/{id}/{name}', function  (string  $id, string  $name) {
    // ...
})->where(['id'  =>  '[0-9]+', 'name'  =>  '[a-z]+']);

Router::get('/user/profile', function  () {
    // ...
})->name('profile');

Router::group(['prefix' => '/user'], function () {
    // here all routes will be prefixed with /user
    Router::get('/update', fn () => die('not implemented')); /* /user/update */
});

Router::redirect('/old', '/new');

Router::redirect('/old', '/new', 301);

Router::permanentRedirect('/old', '/new');

Router::get('/user/{id}', function ($id) {
    // ...
})->name('user.profile');

$url = route('user.profile', 1);
// $url = 'http://example.com/user/1'


namespace Middlewares;

use Mrfoo\PHPRouter\Core\Middleware;

class AuthMiddleware extends Middleware
{
    public function handle()
    {
        if (!isset($_SESSION['user_id'])) {
            // redirect to login page
            header('Location: /login');
            exit;
        }
    }
}

Router::get('/user/profile', function () {
    // ...
})->name('user.profile')->middleware(AuthMiddleware::class);

Router::get('/user/profile', function () {
    // ...
})->name('user.profile')->middleware([AuthMiddleware::class, AnotherMiddleware::class]);


namespace Middlewares;

use Mrfoo\PHPRouter\Core\Middleware;

class AuthMiddleware extends Middleware
{
    public function handle()
    {
        if (!isset($_SESSION['user_id'])) {
            // redirect to login page
            header('Location: /login');
            exit;
        }
    }

    public function terminate()
    {
        // do some cleanup
    }
}


rfoo\PHPRouter\Router;
use Controllers\UserController;

Router::get('/greet', function () {
    echo 'hello everyone';
})->name('greeting');

Router::post('/user/create', function () {
    // ...
    $id = $_POST['user_id']; // make sure to sanitize your inputs!
})->name('user.create');

Router::patch('/user/profile', [UserController::class, 'update'])->name('user.profile.update');

// make it bun dem!
Router::run();
bash
composer 
shell
php -S localhost:8888 index.php