PHP code example of nabeelalihashmi / lightrouter

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

    

nabeelalihashmi / lightrouter example snippets



function getRoutes()
{
    return [
        ['GET', '/', [HomeController::class, 'index'], []],
        ['POST', '/', [HomeController::class, 'posts'], [LoginCheck::class]],
        ['GET', '/user/someuser/icon', [HomeController::class, 'index'], [LoginCheck::class]],
        ['GET', '/user/.+', [HomeController::class, 'user'], [LoginCheck::class]]
    ];
}


$router = new Router;
$router->setRoutes(getRoutes());
$router->setNotFound(function() {
    header('HTTP/1.1 404 Not Found');
    echo '404 Not Found';
});

$router->run();



namespace App\Controllers;

class HomeController
{
    public function index()
    {
        echo 'Hi';
    }

    public function posts() {
        echo 'My posts';
    }

    public function user($id) {
        echo 'Here';
        var_dump($id);
    }
}



namespace App\Middlewares;

use IconicCodes\LightRouter\IMiddleware;

class LoginCheck implements IMiddleware{
    public function handle() {
        return true;
    }
}

$router->addRoute('GET', '/user/{arg1}/{arg2}', [HomeController::class, 'user'], [MyMiddleware::class]);

class HomeController {
    public function user($id, $name) {
        var_dump($id);
        var_dump($name);
    }
}

$router->run();

$router->setNotFound(function() {
    header('HTTP/1.1 404 Not Found');
    echo '404 Not Found';
});