PHP code example of rammewerk / router

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

    

rammewerk / router example snippets


$router = new Rammewerk\Component\Router\Router();

$router->add('/', RouteActions::class);

$router->find();

class RouteActions {

    # Handle empty path as well as other unresolved paths.
    public function index(): void {
        echo 'Hello index';
    }
    
    # Handle paths that starts with '/blog/hello/'
    public function blog_hello(): void {
        echo 'Welcome to my blog!';
    }
      
}

$router->add('/', function() {
    echo 'Hello index';
});

$router->add('/blog/hello', function() {
    echo 'Welcome to my blog!';
});

$router->add('/', function(): string {
    return 'Hello index';
});

# Value will be whatever the route returns
$value = $router->find();

$router->add('/product/item', function(string $id) {
    echo "Showing product item with ID: $id";
});

$router->add('/page', function( ...$params ) {
    ...
})

$router->add('/page', RouterActions::class )

$router->registerDependencyLoader( function( string $class_name ) => use($container) {
    return $container->create($class_name);
});

$router->add("/product/item/", function( ProductController $product, string $id ) {
    $product->showItem( $id );
});

namespace Module\Product;

class ProductRouteActions {

    # Will handle /product/
    public function index(): void {
        echo 'Default product page when visiting base level of route: /';
    }
    
    # Will handle /product/item/{id}
    public function item( string $id ): void {
        echo "Implement loading of product item with id $id";
    }
    
    # Will handle /product/list/all/
    public function list_all(): void {
        echo "Implement list of all products"
    }
    
}

$router->add('/product', ProductRouteActions::class);

class ProductRouteActions {

    ...
    
    # Will handle /product/update/{id}
    public function update( string $id ): void {
        # Handle product update for product of ID = $id
    }
    
}

$router->registerClassDependencyLoader( function( \ReflectionClass $class) use ($container) {
    return $container->create($class->name);
});

$router->classAuthenticationMethod('hasRouteAccess');

class SecureBlogRoutes {

    // Access to any route in this class is granted if this returns true.
    public function hasRouteAccess(): bool {
        return ! empty($_SESSION['user_id']);
    }
    
    // This route will only load if 'hasRouteAccess' returns true.
    public function index(): void {
        echo 'Welcome to my secure blog!';
    }
    
}