PHP code example of snicco / http-routing

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

    

snicco / http-routing example snippets


use Snicco\Component\HttpRouting\Routing\Cache\FileRouteCache;use Snicco\Component\HttpRouting\Routing\Cache\NullCache;
use Snicco\Component\HttpRouting\Routing\RouteLoader\DefaultRouteLoadingOptions;
use Snicco\Component\HttpRouting\Routing\RouteLoader\PHPFileRouteLoader;
use Snicco\Component\HttpRouting\Routing\Router;
use Snicco\Component\HttpRouting\Routing\UrlGenerator\UrlGenerationContext;

$context = new UrlGenerationContext('snicco.io');

$route_loading_options = new DefaultRouteLoadingOptions(
    '/api/v1' // the base-prefix for API routes
);
$route_loader = new PHPFileRouteLoader(
    [__DIR__.'/routes'], // directories of "normal" routes
    [__DIR__.'/routes/api'], // directories of "API" routes, optional
    $route_loading_options,
);

// during development
$route_cache = new NullCache();
// during production
$route_cache = new FileRouteCache('/path/to/cache_dir/route_cache.php');

$router = new Router(
     $context,
     $route_loader,
     $route_cache
//     $admin_area  This is a simple interface that you can implement if you use admin routes.
);


use Snicco\Component\HttpRouting\Routing\Router;

/**
* @var Router $router 
*/
$router = /* */

$router->routes(); // Returns an instance of RouteCollection

$router->urlGenerator(); // Returns an instance of UrlGenerator

$router->urlMatcher(); // Returns an instance of UrlMatcher

$router->adminMenu(); // Returns an instance of AdminMenu


// ./routes/frontend.php
use Snicco\Component\HttpRouting\Routing\RoutingConfigurator\WebRoutingConfigurator;

return function (WebRoutingConfigurator $configurator ) {
    //
}

// ./routes/admin.php
use Snicco\Component\HttpRouting\Routing\RoutingConfigurator\AdminRoutingConfigurator;

return function (AdminRoutingConfigurator $configurator ) {
    //
}

use Snicco\Component\HttpRouting\Routing\RoutingConfigurator\WebRoutingConfigurator;

/**
* @var WebRoutingConfigurator $configurator 
*/
$configurator = /* */

$configurator->get(
   'posts.index', // The route name MUST BE UNIQUE.
   '/posts', // The route pattern
   [PostController::class, 'index'] // The controller for the route.
);

$configurator->post('posts.create', '/posts', [PostController::class, 'create']);

$configurator->put('posts.update', '/posts/{post_id}', [PostController::class, 'update']);

$configurator->delete('posts.delete', '/posts/{post_id}', [PostController::class, 'delete']);

$configurator->patch(/* */);

$configurator->options(/* */);

$configurator->any(/* */);

$configurator->match(['GET', 'POST'], /* */);


$configurator->get(
   'route_name',
   '/posts/{post}/comments/{comment?}',
   PostController::class
);

$configurator->get(
   'route_name',
   '/posts/{post}/comments/{comment?}/',
   PostController::class
);

use Snicco\Component\HttpRouting\Routing\Route\Route;
use Snicco\Component\HttpRouting\Routing\RoutingConfigurator\WebRoutingConfigurator;

/**
* @var WebRoutingConfigurator $configurator 
*/
$configurator->get(
   'route1',
   '/user/{id}/{name}',
    PostController::class
)->me');
$route->

use Snicco\Component\HttpRouting\Routing\Route\Route;
use Snicco\Component\HttpRouting\Routing\RoutingConfigurator\WebRoutingConfigurator;

/**
* @var WebRoutingConfigurator $configurator 
*/
$configurator->get('route1', '/route1', InvokableController::class)
              // middleware as an alias.
             ->middleware('auth')
             
             // adding multiple middleware
             ->middleware([PSR15MiddlewareOne::class, PSR15MiddlewareTwo::class]);
             
             // passing comma separated arguments
             ->middleware('can:manage_options,1');

use Snicco\Component\HttpRouting\Routing\Route\Route;
use Snicco\Component\HttpRouting\Routing\RoutingConfigurator\WebRoutingConfigurator;

/**
* @var WebRoutingConfigurator $configurator 
*/
$configurator->get('route1', '/route1', InvokableController::class)
             
             ->condition(OnlyIfUserAgentIsFirefox::class)
                
             // passing arguments   
             ->condition(OnlyIfHeaderIsPresent::class, 'X-CUSTOM-HEADER');

use Snicco\Component\HttpRouting\Routing\RoutingConfigurator\WebRoutingConfigurator;

/**
* @var WebRoutingConfigurator $configurator 
*/
$configurator
    ->name('users')
    ->prefix('/base/users')
    ->middleware('auth')
    ->namespace('App\\Http\\Controllers')
    ->group(function (WebRoutingConfigurator $configurator) {
        
        // The route name will be users.profile
        // The route pattern will be /base/users/profile/{user_id}
        // The controller definition will be [App\\Http\\Controllers\\ProfileController::class, 'index']
        // The middleware is [auth, auth-confirmed] 
        $configurator->get('profile', '/profile/{user_id}', 'ProfileController@index')
                     ->middleware('auth-confirmed');
            
        $configurator->/* */->group(/* */);    
    });


namespace App\Controller;

use Snicco\Component\HttpRouting\Http\Psr7\Request;

class RouteController {
    
    public function __invoke(Request $request){
        //
    }
    
    public function withoutRequest(string $route_param){
        //
    }
        
    public function withRequestTypehint(Request $request, string $route_param){
        //
    }
        
}

// Valid ways to define a controller:

$configurator->get('route1', '/route-1', RouteController::class)

$configurator->get('route2', '/route-2/{param}', [RouteController::class, 'withoutRequest']);

$configurator->get('route3', '/route3/{param}', 'App\\Controller\\RouteController@withRequestTypehint');
// or
$configurator->namespace('App\\Controller')->get('route3', '/route3/{param}', 'RouteController@withRequestTypehint');


use Snicco\Component\HttpRouting\Routing\RoutingConfigurator\WebRoutingConfigurator;

/**
* @var WebRoutingConfigurator $configurator
*/

$configurator->redirect('/foo', '/bar', 301);

$configurator->redirectAway('/foo', 'https://external-site.com', 302);

$configurator->redirectToRoute('/foo', 'route1', 307);

use Snicco\Component\HttpRouting\Routing\RoutingConfigurator\WebRoutingConfigurator;

/**
* @var WebRoutingConfigurator $configurator
*/

$configurator->view('/contact', 'contact.php');

// .routes/admin.php
use Snicco\Component\HttpRouting\Routing\Admin\AdminMenu;
use Snicco\Component\HttpRouting\Routing\Admin\AdminMenuItem;
use Snicco\Component\HttpRouting\Routing\RoutingConfigurator\AdminRoutingConfigurator;

/**
* @var AdminRoutingConfigurator $configurator
*/

$configurator->name('my-plugin')
             ->middleware('my-plugin-middleware')
             ->group(function (AdminRoutingConfigurator $configurator) {
             
                $parent_route = $configurator
                   ->page('overview', '/admin.php/overview', OverViewController::class)
                   ->middleware('parent-middleware');
                
                $configurator->page(
                   'settings', 
                   '/admin.php/settings', 
                   SettingsController::class, 
                   [
                      // Explicitly configure menu item attributes.
                      AdminMenuItem::MENU_TITLE => 'Custom settings title'
                   ]
                   $parent_route // Set a parent route to create a menu hierarchy. Middleware is inherited.
                );
                
             });

use Snicco\Component\HttpRouting\Routing\UrlMatcher\RoutingResult;
use Snicco\Component\HttpRouting\Routing\UrlMatcher\UrlMatcher;

$router = /* */

/** @var  $url_matcher */
$url_matcher = $router->urlMatcher();

$psr_server_request = /* create any psr7 server request here. */

$routing_result = $url_matcher->dispatch($psr_server_request);

$routing_result->isMatch();
$routing_result->route();
$routing_result->decodedSegments();

use Snicco\Component\HttpRouting\Routing\Router;
use Snicco\Component\HttpRouting\Routing\UrlGenerator\UrlGenerator;

// In a route file:
$configurator->get('route1', '/route1/{param1}/{param2}', RouteController::class)
              ->1/foo/1

$url = $url_generator->toRoute('route1', ['param1' => 'foo', 'param2' => '1'], UrlGenerator::ABSOLUTE_URL); 
var_dump($url); // https://snicco.io/route1/foo/1 (host and scheme depend on your UrlGenerationContext)


// This will throw an exception because param2 is not a number
$url_generator->toRoute('route1', ['param1' => 'foo', 'param2' => 'bar']); 

/**
* @var Router $router 
*/
$router = /* */

$admin_menu = $router->adminMenu();

foreach ($admin_menu->items() as $menu_item) {
    // register the menu item somewhere.
}

use Psr\Container\ContainerInterface;
use Snicco\Component\HttpRouting\Middleware\MiddlewarePipeline;
use Snicco\Component\Psr7ErrorHandler\ProductionErrorHandler;

/**
* @var ContainerInterface $psr_11_container 
*/
$psr_11_container = /* */

/**
* @var ProductionErrorHandler 
*/
$psr7_error_handler = /* */

$pipeline = new MiddlewarePipeline(
    $psr_11_container,
    $psr7_error_handler
);

use Snicco\Component\HttpRouting\Http\Psr7\Request;
use Snicco\Component\HttpRouting\Middleware\MiddlewarePipeline;

/**
* @var MiddlewarePipeline $pipeline
*/
$pipeline = /* */

$response = $pipeline
               ->send($server_request)
               ->through([
                   Psr15MiddlewareOne::class,
                   Psr15MiddlewareTwo::class,
                ])->then(function (Request $request) {
                    // Throw exception or return a default response.
                    throw new RuntimeException('Middleware pipeline exhausted without returning response.');
                });

use Snicco\Component\HttpRouting\Middleware\RoutingMiddleware;

$routing_middleware = new RoutingMiddleware(
    $router->urlMatcher();
);

use Snicco\Component\HttpRouting\Middleware\RouteRunner;

$pipeline = /* This can be the same pipeline we created initially. The pipeline is immutable anyway. */
$psr_11_container = /* */
$middleware_resolver = /* */

$route_runner = new RouteRunner($pipeline, $middleware_resolver, $psr_11_container);

$response = $pipeline->send($server_request)
                     ->through([
                        $routing_middleware,
                        $route_runner   
                     ])->then(function () {
                        throw new RuntimeException('Middleware pipeline exhausted.');
                     });

use Snicco\Component\HttpRouting\Middleware\MiddlewareResolver;

// The following four middleware groups can be set to always be applied, even if no route matched.
$always_run = [
    'global'
    'frontend',
    'admin',
    'api'
]

// This configures the short aliases we used in our route definitions
$middleware_aliases = [
    'auth' => AuthenticateMiddleware::class
]

// An alias can also be a middleware group.
// Middleware groups can contain other groups.
$middleware_groups = [
    'group1' => [
        'auth', // group contains alias
        SomePsr15Middleware::class    
    ],
    'group2' => [
        'group1,' // fully contains group1
         SomeOtherPsr15Middleware::class    
    ],
    'global' => [],
    'frontend' => [ ],
    'api' => [
        RateLimitAPI::class    
    ],
    'admin' => []   
];

// A list of class names, the 0-index has the highest priority, meaning that it will
// always run first.
$middleware_priority = [
    SomePsr15Middleware::class,
    SomeOtherPsr15Middleware::class
];

$middleware_resolver = new MiddlewareResolver(
    $always_run,
    $middleware_aliases, 
    $middleware_groups,
    $middleware_priority
);

use Snicco\Component\HttpRouting\Middleware\MiddlewareResolver;

$middleware_resolver = new MiddlewareResolver();

$store_me = $middleware_resolver->createMiddlewareCache(
    $router->routes(),
    $psr_11_container
);

file_put_contents('/path/to/cache-dir/middleware-cache.php', ' return ' . var_export($store_me, true) . ';');

list($route_map, $request_map) = 

your-project-root
├── routes/
│   ├── frontend.php
│   ├── admin.php
├── api-routes/
│   ├── v1.php
└── ...