PHP code example of alexya-framework / router

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

    

alexya-framework / router example snippets



$Router = new \Alexya\Router\Router();
// will route all requests of `/`
// /forum
// /forum/thread/1
// /blog
// /blog/post/1

$Router = new \Alexya\Router\Router("blog");
// will route all requests of `/blog` (if `/forum` is requested, it will be ignored).
// /blog
// /blog/post/1



$Router->add("/blog/post/([0-9]*)", function($id) {
    echo "Requested post: {$id}";
});

$Router->add("/forum/thread/([0-9]*)", function($id) {
    echo "Requested thread: {$id}";
}, ["GET", "POST"]);



$Router->add([
    [
        "/blog/post/([0-9]*)",
        function($id) {
            echo "Requested post: {$id}";
        }
    ],
    [
        "/forum/thread/([0-9]*)",
        function($id) {
            echo "Requested thread: {$id}";
        },
        ["GET", "POST"]
    ]
])


$Router = new \Alexya\Router\Router("blog");

$Router->add("/post/([0-9]*)", function($id) {
    echo "Requested post: {$id}";
}, "GET");

$Router->add("{DEFAULT}", function() {
    echo "The page doesn't exist!";
});

//  |           Request          |         Response       |
//  |----------------------------|------------------------|
//  | GET  /blog/post/           | Requested post:        |
//  | GET  /blog/post/1          | Requested post: 1      |
//  | POST /blog/post/3416321341 | The page doesn't exist |
//  | GET  /blog/post/a          | The page doesn't exist |
//  | POST /post/                | The page doesn't exist |
//  | GET  /post/1               | The page doesn't exist |



$router = new \Alexya\Router\Router();
$router->add("(.*)", function() {
    echo "Page requested";
});
$router->add("/User/([a-zA-Z]*)", function($user) {
    echo "User {$user}";

    return false; // Exit chain
});
$router->add("/User/([a-zA-Z]*)/(.*)", function($user, $action) {
    echo "User {$user}, action {$action}";
});

$router->route(true);

// Request URI: /User/test/asdf
// Output:
//  Page requested
//  User test