PHP code example of jdz / router

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

    

jdz / router example snippets


use JDZ\Router\Router;
use Symfony\Component\HttpFoundation\Request;

$request = Request::createFromGlobals();
$router = new Router(__DIR__ . '/routes/', $request);

// Load routes from YAML files
$router->addYml('routes.yml');
$router->addYml('api-routes.yml');

use JDZ\Router\Generator\Routes;
use JDZ\Router\Generator\Route;

$routes = new Routes();

// Add routes using Route objects
$routes->addRoutes([
    new Route('/home/', 'Home', [
        'component' => 'main',
        'task' => 'home',
    ]),
    
    new Route('/search/', 'Search', [
        'component' => 'search',
        'task' => 'display',
    ]),
]);

// Add route using array notation
$routes->addRoutes([
    [
        'url' => '/contact/',
        'name' => 'Contact',
        'vars' => [
            'component' => 'contact',
            'task' => 'form',
        ],
    ],
]);

// Create and add a route
$route = $routes->createRoute('/about/', 'About', [
    'component' => 'page',
    'task' => 'display',
    'slug' => 'about',
]);
$routes->addRoute($route);

use Symfony\Component\Yaml\Yaml;

// Export routes to array format
$routesArray = $routes->export();

// Write to YAML file
$yamlContent = Yaml::dump($routesArray, 4, 2);
file_put_contents('routes.yml', $yamlContent);

// Match the current request
$match = $router->match();

if ($match !== false) {
    $component = $match['component'];
    $task = $match['task'];
    // Handle the matched route
}

// Match a specific path
$match = $router->match('/search/');

// Generate URL for a named route
$url = $router->url('search');
// Returns: /search/

// Generate URL with parameters
$url = $router->url('userProfile', ['id' => 123]);
// Returns: /user/123/

// Generate absolute URL
$absoluteUrl = $router->url('search', [], true);
// Returns: https://example.com/search/

use JDZ\Router\Route;

$route = new Route($router, $request);

try {
    $route->load();
    
    // Check if it's a JSON endpoint
    if ($route->isJson()) {
        header('Content-Type: application/json');
    }
    
    // Access parsed parameters
    $component = $request->query->get('component');
    $task = $request->query->get('task');
    
} catch (\JDZ\Router\RouterException $e) {
    // Handle route not found
    http_response_code(404);
    echo 'Page not found';
}

// Add redirect paths for legacy URLs
$router->addRedirectPaths([
    '/old-path/' => '/new-path/',
    '/legacy/page/' => '/page/',
]);

// Routes with JSON format
$route = new Route('/json/api/', 'ApiEndpoint', [
    'component' => 'api',
    'task' => 'getData',
], true); // true indicates JSON format

// In YAML:
# jsonApi:
#     path: /json/api/
#     defaults:
#         _format: json
#         component: api
#         task: getData
#     

$route = new Route('/form/', 'ContactForm', [
    'component' => 'contact',
    'task' => 'form',
]);
$route->setMethods(['GET', 'POST']);

$route = new Route('/vault/', 'Vault', [
    'component' => 'secure',
]);
$route->setOption('ignoreLastUrl', true);

use JDZ\Router\Generator\RoutesImmutable;

// Create immutable route collection
$immutableRoutes = new RoutesImmutable([
    new Route('/home/', 'Home'),
    new Route('/about/', 'About'),
]);

// Add new routes (allowed)
$immutableRoutes->addRoute(new Route('/contact/', 'Contact'));

// Try to modify existing route (throws exception)
try {
    $immutableRoutes->addRoute(new Route('/home/', 'HomeModified'));
} catch (\Exception $e) {
    // Routes are immutable
}