PHP code example of echo-fusion / routemanager

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

    

echo-fusion / routemanager example snippets


    use EchoFusion\RouteManager\RouteMatch;
    use EchoFusion\RouteManager\Router;
    
    $routeMatcher = new RouteMatch();
    $router = new Router($routeMatcher);
    

    use Psr\Http\Message\ServerRequestInterface;
    
    // Define a simple route
    $router->post(
        name: 'api.store', 
        path: '/api', 
        action: [ApiController::class, 'store']
    );
    
    // Define a route with parameter constraints
    $router->get(
        name: 'blog-show',
        path: '/post/{id}/detail/{slug}',
        action: function (int $id, string $slug, ServerRequestInterface $request) {
            // Your action code here
            var_dump($id, $slug);
        },
        constraints: [
            'id' => '[0-9]+',
            'slug' => '[a-z0-9\-]+',
        ]
    );
    

    try {
        $routeMatch = $router->dispatch($request);
        
        $action = $routeMatch->getRoute()->getAction();
        $params = array_merge($routeMatch->getParams(), [$request]);
    
        // Execute the action (callable or controller method)
        return call_user_func_array($action, $params);
    } catch (EchoFusion\RouteManager\Exceptions\RouteNotFoundException $e) {
        // Handle route not found
    } catch (Throwable $exception) {
        // Handle other errors
    }
    

    use EchoFusion\RouteManager\Providers\RouteManagerProvider;
    use YourApp\Container;
    
    $provider = new RouteManagerProvider();
    $provider->register($container);
    

    $routes = [
        'home' => [
            'method' => 'GET',
            'path' => '/',
            'action' => fn () => 'Welcome to the homepage',
        ],
        'blog_show' => [
            'method' => 'GET',
            'path' => '/post/{id}/detail/{slug}',
            'action' => function (int $id, string $slug, ServerRequestInterface $request) {
                // Route action code here
            },
            'constraints' => [
                'id' => '[0-9]+',
                'slug' => '[a-z0-9\-]+',
            ],
        ],
    ];
    
    $provider->boot($container, $routes);
    

    use EchoFusion\Contracts\RouteManager\RouterInterface;
    use EchoFusion\RouteManager\Exceptions\RouteNotFoundException;
    
    try {
        $router = $container->get(RouterInterface::class);
        $routeMatch = $router->dispatch($request);
    } catch (RouteNotFoundException $e) {
        // Handle route not found
    } catch (Throwable $exception) {
        // Handle other errors
    }
    
 bash
$ composer