PHP code example of guahanweb / php-router

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

    

guahanweb / php-router example snippets



// Include the namespace
use GuahanWeb\Http;

// Get a router instance
$router = Http\Router::instance();

// Register a route
$router->get('/', function ($req, $res) {
    $res->send('Hello, world!');
});

// Tell the router to start
$router->process();

$router->get($route, $handler);
$router->post($route, $handler);
$router->put($route, $handler);
$router->delete($route, $handler);

// multiple verbs
$router->route(['POST', 'PUT'], $route, $handler);

// wildcard for all supported verbs
$router->route('*', $route, $handler);

// capture a username
$router->get('/profile/{username}', function ($req, $res) {
    var_dump($req->username);
});

// match a path with json extension
// URI: /api/v1/my_method/json
$router->get('/api/{path*}/json', function ($req, $res) {
    $res->send($req->path); // v1/my_method
});

// route all image requests to a handler
$router->get('/img/{image*}', function ($req, $res) {
    ImageManager::serve($req->image);
});

echo $req->method;

$router->post('/api/user', function ($req, $res) {
    if ($req->headers['Content-Type'] == 'application/json') {
        // request has JSON payload
    }
});

$router->post('/calendar', function ($req, $res) {
    if (!isset($req->query['month'])) {
        $res->send('Please select a month!');
    } else {
        $res->send(Calendar::render($req->query['month']));
    }
});

$router->get('/profile/{username}', function ($req, $res) {
    $res->send($req->uri);
});

$router->route('*', '/admin', function ($req, $res) {
    $res->send('What do you think you are doing?', 500);
});

// examine request from any verbs
$router->route('*', '/info', function ($req, $res) {
    $res->send(array(
        'method' => $req->method,
        'uri' => $req->uri,
        'query' => $req->query,
        'headers' => $req->headers,
        'body' => $req->body
    ));
});

$ composer