PHP code example of ft / just-routes

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

    

ft / just-routes example snippets


final class MyController {

}

#[RequestMapping(value: "/foobar")]
final class MyController {

}

#[RequestMapping(value: "/foobar")]
final class MyController {

    #[GetMapping]
    function voidMethod() { // maps to GET /foobar
    }

    #[GetMapping(value: "/bazz")]
    function get_bazz() { // maps to GET /foobar/bazz
        echo "bazz";
    }

}

RouteFactory::registerController(MyController::class);

#[RequestMapping(value: "/foobar")]
final class MyController {

    #[GetMapping]
    function voidMethod() { // maps to GET /foobar
        throw new IllegalArgumentException("Illegal");
    }

    #[GetMapping(value: "/bazz")]
    function get_bazz() { // maps to GET /foobar/bazz
        throw new IllegalArgumentException("Illegal");
    }

    #[ExceptionHandler(IllegalArgumentException::class)]
    function handle_illegal_arg_exc(IllegalArgumentException $exc, string $path) {
        //swallowed IllegalArgumentException only from this controller's routes
    }

}

RouteFactory::registerController(MyController::class);
RouteFactory::onException(IllegalArgumentException::class, function (string $path) {
    echo "Caught globally";
});

RouteFactory::registerController(MyController::class);
RouteFactory::onNotFound(function ($path) {
    echo "$path not found";
});

RouteFactory::registerController(MyController::class);
RouteFactory::dispatch();

    #[RequestMapping(value: "/foobar")]
    final class MyController {

        #[GetMapping("/id/{id}")]
        public function get_foo(int $id, #[RequestParam] string $internal, #[RequestParam] array $foos) {
            // Example req:
            // GET /foobar/id/1?internal=true&foos[]=1&foos[]=2&foos[]=3
        }
    }
    

    #[RequestMapping(value: "/foobar")]
    final class MyController {

        #[GetMapping("/id/{id}")]
        public function get_foo(int $id, #[RequestHeader] string $referer) {

        }
    }
    

#[RequestMapping(value: "/foobar")]
final class MyController {

    #[GetMapping(value: "/name/{name}/age/{age}")]
    function get_for_name_age(string $name, int $age) {
        // example req
        // GET /foobar/name/John/age/18
    }

}