PHP code example of elzobrito / olivia-router

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

    

elzobrito / olivia-router example snippets



$csrfToken = bin2hex(random_bytes(32));

setcookie('OLIVIA_APP_NAMESPACE', 'App', 0, '/');
setcookie('OLIVIA_CONTROLLER_FOLDER', 'Controller', 0, '/');
setcookie('OLIVIA_MIDDLEWARE_FOLDER', 'Middleware', 0, '/');
setcookie('OLIVIA_BASE_PATH', '', 0, '/');
setcookie('OLIVIA_CSRF', 'true', 0, '/');
setcookie('OLIVIA_CSRF_TOKEN', $csrfToken, 0, '/', '', true, true);



er = new OliviaRouter\Router();

$router->get('/', 'home#index');
$router->post('/users', 'user#store');
$router->put('/users/{id}', 'user#update');
$router->delete('/users/{id}', 'user#destroy');

$router->middleware('auth')->get('/dashboard', 'dashboard#index');

$requestData = [
    'REQUEST_METHOD' => $_SERVER['REQUEST_METHOD'],
    'REQUEST_URI' => $_SERVER['REQUEST_URI'],
    'POST' => $_POST,
    'GET' => $_GET,
    'COOKIE' => $_COOKIE,
    'CONTENT_TYPE' => $_SERVER['CONTENT_TYPE'] ?? null,
];

$router->execute($requestData);



namespace App\Middleware;

use OliviaRouter\RequestHandler;

class Auth implements RequestHandler
{
    public function handle()
    {
        if (!isset($_SESSION['user'])) {
            header('Location: /login');
            exit;
        }
    }
}

$router->middleware('auth')->get('/dashboard', 'dashboard#index');



use OliviaRouter\Request;
use OliviaRouter\Route;
use OliviaRouter\Trie;

$request = new Request(
    $_SERVER['REQUEST_METHOD'],
    $_SERVER['REQUEST_URI'],
    $_POST,
    $_GET,
    $_SERVER,
    $_SERVER['CONTENT_TYPE'] ?? null
);

$trie = new Trie();
$route = new Route('GET', '/users/{id}', 'user#show');

if ($route->matches($request, $trie)) {
    $params = $route->getParams();
}
bash
composer dump-autoload
text
OliviaRoute/
├── src/
│   ├── ControllerFactory.php
│   ├── MiddlewareFactory.php
│   ├── Request.php
│   ├── RequestHandler.php
│   ├── Route.php
│   ├── Router.php
│   ├── RouterConfig.php
│   ├── RouterDispatcher.php
│   └── Trie.php
├── vendor/
├── composer.json
└── README.md