PHP code example of inanepain / routing

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

    

inanepain / routing example snippets


class MainController {
    ...

    #[Route(path: '/', name: 'home')]
    public function home(): void {
        ...
        echo <<<HTML
...
HTML;
    }

    ...

    #[Route(path: '/product/{product}', name: 'product', )]
    public function productTask(array $params): void {
        $sql = "...where product_id = '{$params["product"]}'";
        ...
        echo <<<HTML
...
HTML;
    }

    ...
}

use App\Controller\MainController;
use Inane\Routing\Router;

ing files in web dir
if (file_exists($file) && !is_dir($file)) return false;

$router = new Router();
$router->addRoutes([MainController::class]);

if ($match = $router->match()) {
    $controller = new $match['class']();
    $controller->{$match['method']}($match['params']);
} else {
    throw new Exception('Request Error: Unmatched `file` or `route`!');
}


class IndexController extends AbstractController {
    ...

    #[Route(path: '/', name: 'home')]
    public function indexTask(): array {
        ...
    }

    ...

    #[Route(path: '/product/{product}', name: 'product', )]
    public function productTask(): array {
        ...
    }

    ...

    #[Route(path: '/product/{product}/review/{id<\d+>}', name: 'product-review')]
    public function reviewTask(): array {
        ...
    }

    ...
}

class Application {
    ...

    protected function initialise(): void {
        ...
        $this->router = new Router([
            IndexController::class,
            ...
            WhoopsController::class,
            ...
        ]);
        ...
    }

    ...

    public function run(): void {
        ...
        if ($match = $this->router->match()) {
            $controller = new $match['class']($match['params']);
            $data = $controller->{$match['method']}();
            ...
            $body = $this->renderer->render($template, $data);
            ...
        }
        ...
    }

    ...
}