PHP code example of jasny / switch-route

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

    

jasny / switch-route example snippets


function getRoutes(): array
{
    return [
        'GET      /'                  => ['controller' => 'InfoController'],

        'GET      /users'             => ['controller' => 'UserController', 'action' => 'listAction'],
        'POST     /users'             => ['controller' => 'UserController', 'action' => 'addAction'],
        'GET      /users/{id}'        => ['controller' => 'UserController', 'action' => 'getAction'],
        'POST|PUT /users/{id}'        => ['controller' => 'UserController', 'action' => 'updateAction'],
        'DELETE   /users/{id}'        => ['controller' => 'UserController', 'action' => 'deleteAction'],

        'GET      /users/{id}/photos' => ['action' => 'ListPhotosAction'],
        'POST     /users/{id}/photos' => ['action' => 'AddPhotosAction'],

        'POST     /export'            => ['

class UserController
{
    public function updateAction(string $id)
    {
        // ...
    }
}

function getRoutes(): array
{
    return [
        'GET      /'                  => ['controller' => 'info'],

        'GET      /users'             => ['controller' => 'user', 'action' => 'list'],
        'POST     /users'             => ['controller' => 'user', 'action' => 'add'],
        'GET      /users/{id}'        => ['controller' => 'user', 'action' => 'get'],
        'POST|PUT /users/{id}'        => ['controller' => 'user', 'action' => 'update'],
        'DELETE   /users/{id}'        => ['controller' => 'user', 'action' => 'delete'],

        'GET      /users/{id}/photos' => ['action' => 'list-photos'],
        'POST     /users/{id}/photos' => ['action' => 'add-photos'],

        'POST     /export'            => ['

$stud = fn($str) => strtr(ucwords($str, '-'), ['-' => '']);
$camel = fn($str) => strtr(lcfirst(ucwords($str, '-')), ['-' => '']);

$invoker = new Invoker(function (?string $controller, ?string $action) use ($stud, $camel) {
    return $controller !== null
        ? [$stud($controller) . 'Controller', $camel($action ?? 'default') . 'Action']
        : [$stud($action) . 'Action', '__invoke'];
});

use Jasny\SwitchRoute\Generator;

// Always generate in development env, but not in production.
$overwrite = (getenv('APPLICATION_ENV') ?: 'dev') === 'dev';

$generator = new Generator();
$generator->generate('route', 'generated/route.php', 'getRoutes', $overwrite);



$method = $_SERVER["REQUEST_METHOD"];
$path = rawurldecode(parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH));

route($method, $path);

use Jasny\SwitchRoute\Generator;
use Jasny\SwitchRoute\Invoker;

// Always generate in development env, but not in production.
$overwrite = (getenv('APPLIACTION_ENV') ?: 'dev') === 'dev';

$routeGenerator = new Generator(new Generator\GenerateRouteMiddleware());
$routeGenerator->generate('App\Generated\RouteMiddleware', 'generated/RouteMiddleware.php', 'getRoutes', $overwrite);

$invoker = new Invoker();
$invokeGenerator = new Generator(new Generator\GenerateInvokeMiddleware($invoker));
$invokeGenerator->generate('App\Generated\InvokeMiddleware', 'generated/InvokeMiddleware.php', 'getRoutes', $overwrite);

use App\Generated\RouteMiddleware;
use App\Generated\InvokeMiddleware;
use Jasny\SwitchRoute\NotFoundMiddleware;
use HttpMessage\Factory as HttpFactory;
use HttpMessage\ServerRequest;
use Relay\Relay;

$httpFactory = new HttpFactory();

$middleware[] = new RouteMiddleware();
$middleware[] = new NotFoundMiddleware($httpFactory);
$middleware[] = new InvokeMiddleware(fn($controllerClass) => new $controllerClass($httpFactory));

$relay = new Relay($middleware);

$request = new ServerRequest($_SERVER, $_COOKIE, $_QUERY, $_POST, $_FILES);
$response = $relay->handle($request);

use App\Generated\InvokeMiddleware;

$container = new DI\Container();

$middleware[] = new InvokeMiddleware(fn($controllerClass) => $container->get($controllerClass));

function getRoutes(): array
{
    return [
        'GET /'   => ['controller' => 'info'],
        // ...

        'default' => ['controller' => 'error', 'action' => 'not-found],
    ];
}

class ErrorController
{
    public function notFoundAction(array $allowedMethods)
    {
        if ($allowedMethods === []) {
            http_response_code(404);
        } else {
            http_response_code(405);
            header('Allow: ' . join(', ', $allowedMethods));
        }
        
        echo "<h1>Sorry, there is nothing here</h1>";
    }
}



(new Jasny\SwitchRoute\Generator)->generate('route', 'generated/route.php', 'getRoutes', true);

new Generator(new Generator\GenerateRouteMiddleware());

use Jasny\SwitchRoute\Generator;
use Jasny\SwitchRoute\Invoker;

$invoker = new Invoker();
$generate = new Generator\GenerateFunction($invoker);

$generator = new Generator($generate);
$generator->generate('route', 'generated/route.php', 'getRoutes', true);



$method = $_SERVER["REQUEST_METHOD"];
$path = rawurldecode(parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH));

route($method, $path);

use Jasny\SwitchRoute\Generator;

$generate = new Generator\GenerateRouteMiddleware();

$generator = new Generator($generate);
$generator->generate('RouteMiddleware', 'generated/RouteMiddleware.php', 'getRoutes', true);

[
    'GET /users/{id}/photos'        => ['action' => 'ListPhotosAction', '{page}' => 1],
    'GET /users/{id}/photos/{page}' => ['action' => 'ListPhotosAction'],
];

use Jasny\SwitchRoute\Generator;

$generate = new Generator\GenerateInvokeMiddleware();

$generator = new Generator($generate);
$generator->generate('InvokeMiddleware', 'generated/InvokeMiddleware.php', 'getRoutes', true);

$stud = fn($str) => strtr(ucwords($str, '-'), ['-' => '']);
$camel = fn($str) => strtr(lcfirst(ucwords($str, '-')), ['-' => '']);

$invoker = new Invoker(function (?string $controller, ?string $action) use ($stud, $camel) {
    return $controller !== null
        ? ['App\\' . $stud($controller) . 'Controller', $camel($action ?? 'default') . 'Action']
        : ['App\\' . $stud($action) . 'Action', '__invoke'];
});

use Jasny\SwitchRoute\Generator;
use Jasny\SwitchRoute\NoInvoker;

$invoker = new NoInvoker();
$generate = new Generator\GenerateFunction($invoker);

$generator = new Generator($generate);
$generator->generate('route', 'generated/route.php', 'getRoutes', true);



$method = $_SERVER["REQUEST_METHOD"];
$path = rawurldecode(parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH));

$routeInfo = route($method, $path);

switch ($routeInfo[0]) {
    case 404:
        // ... 404 Not Found
        break;
    case 405:
        $allowedMethods = $routeInfo[1];
        // ... 405 Method Not Allowed
        break;
    case 200:
        $route = $routeInfo[1];
        $vars = $routeInfo[2];
        // ... invoke action based on $route using $vars
        break;
}

use Jasny\SwitchRoute\Generator;

$generate = function (string $name, array $routes, array $structure): string {
    // ... custom logic
    return $generatedCode;
};

$generator = new Generator($generate);
$generator->generate('route', 'generated/route.php', 'getRoutes', true);

$invoker->generateInvocation($route, function ($name, $type = null, $default = null) { /* ... */ }, '(new %s)'); 
json
{
    "scripts": {
        "post-autoload-dump": [
            "bin/generate-router.php"
        ]
    }
}