Search code examples
phproutesaltorouter

PHP AltoRouter - can't get GET request


For some reason I am not able to start AltoRouter. I am trying the most basic call, but nothing is happening. How can I make it work? My index.php file looks like this:

    <?php

    include('settings/autoload.php');

    use app\AltoRouter;

    $router = new AltoRouter;

    $router->map('GET', '/', function(){

        echo 'It is working';
    });

$match = $router->match();

autoload.php:

<?php

require_once('app/Router.php');

Solution

  • Your Problem is that AltoRouter, according to the documentation (and in contrast to the Slim Framework, which seems to have the the same syntax), won't process the request for you, it only matches them. So by calling $router->match() you get all the required information to process the request in any way you like. If you just want to call the closure-function, simply modify your code:

    <?php
    
    // include AltoRouter in one of the many ways (Autoloader, composer, directly, whatever)
    $router = new AltoRouter();
    
    $router->map('GET', '/', function(){
    
        echo 'It is working';
    });
    
    $match = $router->match();
    
    // Here comes the new part, taken straight from the docs:
    
    // call closure or throw 404 status
    if( $match && is_callable( $match['target'] ) ) {
            call_user_func_array( $match['target'], $match['params'] );
    } else {
            // no route was matched
            header( $_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found');
    }
    

    And voilà - now you'll get your desired output!