PHP code example of g4 / aura-router

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

    

g4 / aura-router example snippets



$router_map = 


use Aura\Router\Map;
use Aura\Router\DefinitionFactory;
use Aura\Router\RouteFactory;

$router_map = new Map(new DefinitionFactory, new RouteFactory);


// create the router map object
$router_map = _map->add('home', '/');

// add a simple unnamed route with params
$router_map->add(null, '/{:controller}/{:action}/{:id:(\d+)}');

// add a complex named route
$router_map->add('read', '/blog/read/{:id}{:format}', [
    'params' => [
        'id'     => '(\d+)',
        'format' => '(\..+)?',
    ],
    'values' => [
        'controller' => 'blog',
        'action'     => 'read',
        'format'     => 'html',
    ],
]);


// get the incoming request URI path
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

// get the route based on the path and server
$route = $router_map->match($path, $_SERVER);


if (! $route) {
    // no route object was returned
    echo "No application route was found for that URI path.";
    exit();
}

// does the route indicate a controller?
if (isset($route->values['controller'])) {
    // take the controller class directly from the route
    $controller = $route->values['controller'];
} else {
    // use a default controller
    $controller = 'Index';
}

// does the route indicate an action?
if (isset($route->values['action'])) {
    // take the action method directly from the route
    $action = $route->values['action'];
} else {
    // use a default action
    $action = 'index';
}

// instantiate the controller class
$page = new $controller();

// invoke the action method with the route values
echo $page->$action($route->values);


// $path => "/blog/read/42.atom"
$path = $router_map->generate('read', [
    'id' => 42,
    'format' => '.atom',
]);

$href = htmlspecialchars($path, ENT_QUOTES, 'UTF-8');
echo '<a href="$href">Atom feed for this blog entry</a>';


$map->add("read", "/blog/read/{:id}{:format}", [
	"params" => [
		"id" => "(\d+)",
		"format" => "(\..+)?",
	],
	"values" => [
		"controller" => function ($args) {
		    if ($args['format'] == '.json') {
		        echo header('Content-Type:application/json');
		        echo json_encode($args);
		    } else {
    			$id = (int) $args["id"];
    			echo "Reading blog ID {$id}";
		    }
		},
		"format" => ".html",
	],
]);


$params = $route->values;
$controller = $params["controller"];
unset($params["controller"]);
$controller($params);


$router_map->add('read', '/blog/read/{:id}{:format}', [
    'params' => [
        'id' => '(\d+)',
        'format' => '(\..+)?',
    ],
    'values' => [
        'controller' => 'blog',
        'action' => 'read',
        'id' => 1,
        'format' => '.html',
    ],
    'secure' => false,
    'method' => ['GET'],
    'routable' => true,
    'is_match' => function(array $server, \ArrayObject $matches) {
            
        // disallow matching if referred from example.com
        if ($server['HTTP_REFERER'] == 'http://example.com') {
            return false;
        }
        
        // add the referer from $server to the match values
        $matches['referer'] = $server['HTTP_REFERER'];
        return true;
        
    },
    'generate' => function(\Aura\Router\Route $route, array $data) {
        $data['foo'] = 'bar';
        return $data;
    }
]);


$router_map->add('archive', '/archive/{:year}/{:month}/{:day}');


$router_map->add('archive', '/archive/{:year}/{:month}/{:day}', [
    'params' => [
        'year'  => '([^/]+)',
        'month' => '([^/]+)',
        'day'   => '([^/]+)',
    ],
    'values' => [
        'action' => 'archive',
    ],
]);


$router_map->add('wild_post', '/post/{:id}/{:other*}');

// this matches, with the following values
$route = $router_map->match('/post/88/foo/bar/baz', $_SERVER);
// $route->values['id'] = 88;
// $route->values['other'] = ['foo', 'bar', 'baz'];

// this also matches, with the following values; note the trailing slash
$route = $router_map->match('/post/88/', $_SERVER);
// $route->values['id'] = 88;
// $route->values['other'] = [];

// this also matches, with the following values; note the missing slash
$route = $router_map->match('/post/88', $_SERVER);
// $route->values['id'] = 88;
// $route->values['other'] = [];


$router_map->add('wild_post', '/post/{:id}/{:other+}');

// this matches, with the following values
$route = $router_map->match('/post/88/foo/bar/baz', $_SERVER);
// $route->values['id'] = 88;
// $route->values['other'] = ['foo', 'bar', 'baz'];

// these do not match
$route = $router_map->match('/post/88/', $_SERVER);
$route = $router_map->match('/post/88', $_SERVER);


$router_map->attach('/blog', [
    
    // the routes to attach
    'routes' => [
        
        // a short-form route named 'browse'
        'browse' => '/',
        
        // a long-form route named 'read'
        'read' => [
            'path' => '/{:id}{:format}',
            'params' => [
                'id'     => '(\d+)',
                'format' => '(\.json|\.atom)?'
            ],
            'values' => [
                'format' => '.html',
            ],
        ],
        
        // a short-form route named 'edit'
        'edit' => '/{:id:(\d+)}/edit',
    ],
]);


$router_map->attach('/blog', [
    
    // common params for the routes
    'params' => [
        'id'     => '(\d+)',
        'format' => '(\.json|\.atom)?',
    ],
    
    // common values for the routes
    'values' => [
        'controller' => 'blog',
        'format'     => '.html',
    ],
    
    // the routes to attach
    'routes' => [
        'browse' => '/',
        'read'   => '/{:id}{:format}',
        'edit'   => '/{:id}/edit',
    ],
]);


$attach = [
    // attach to /blog
    '/blog' => [
        
        // prefix for route names
        'name_prefix' => 'projectname.blog.',
        
        // common params for the routes
        'params' => [
            'id' => '(\d+)',
            'format' => '(\.json|\.atom)?',
        ],
    
        // common values for the routes
        'values' => [
            'controller' => 'blog',
            'format' => '.html',
        ],
    
        // the routes to attach
        'routes' => [
            'browse' => '/',
            'read'   => '/read/{:id}{:format}',
            'edit' => '/{:id}/edit',
        ],
    ],
    
    // attach to '/forum'
    '/forum' => [
        // prefix for route names
        'name_prefix' => 'projectname.forum.',
        // ...
    ],

    // attach to '/wiki'
    '/wiki' => [
        // prefix for route names
        'name_prefix' => 'projectname.wiki.',
        // ...
    ],
];

// create the route factory
$route_factory = new \Aura\Router\RouteFactory;

// create the definition factory
$definition_factory = new \Aura\Router\DefinitionFactory;

// create a router map with attached route groups
$router_map = new \Aura\Router\Map($definition_factory, $route_factory, $attach);


// get a routes array from each application packages
$attach = [
    '/blog'  => ctname/wiki/routes.php',
];

// create the route factory
$route_factory = new \Aura\Router\RouteFactory;

// create the definition factory
$definition_factory = new \Aura\Router\DefinitionFactory;

// create a router map with attached route groups
$router_map = new \Aura\Router\Map($definition_factory, $route_factory, $attach);


// create a router map object
$router_map = utes.cache';

// does the cache exist?
if (file_exists($cache)) {
    
    // restore from the cache
    $routes = unserialize(file_get_contents($cache));
    $router_map->setRoutes($routes);
    
} else {
    
    // build the routes using add() and attach() ...
    // ... ... ...
    // ... then save to the cache for the next page load
    $routes = $router_map->getRoutes();
    file_put_contents($cache, serialize($routes));
    
}