Single file routing in php

Keywords: PHP github git

inhere/sroute Very lightweight single file router. Concise and self-defining

referrer the project noahbuschermacaw , but add some feature.

  • Support request method: GET POST PUT DELETE HEAD OPTIONS

  • Support events: found not Found. You can do something when an event is triggered (such as logging, etc.)

  • A parser that supports setting matching routes: SRoute::setMatchedRouteParser(). You can customize how to call matching routing handlers.

  • Supporting automatic matching routing to controllers is like yii. See the configuration item autoRoute.

  • Support manual scheduling of a routing pass method SRoute::dispatchTo()

  • You can also configure nothing, and it works well.

install

{
    "require": {
        "inhere/sroute": "dev-master"
    }
}

Use

First, import classes

use inhere\sroute\SRoute;

Adding routing

// Match GET requests. The processor is a closure Closure
SRoute::get('/', function() {
    echo 'hello';
});

// Matching parameter'test/john'
SRoute::get('/test/(\w+)', function($arg) {
    echo $arg; // 'john'
});

// Matching POST requests
SRoute::post('/user/login', function() {
    var_dump($_POST);
});

// Match GET or POST
SRoute::map(['get', 'post'], '/user/login', function() {
    var_dump($_GET, $_POST);
});

// Allow any request method
SRoute::any('/home', function() {
    echo 'hello, you request page is /home';
});

If'ignoreLastSep'=> true is configured,'/index'is equivalent to'/index/'

Using Controller Method

SRoute::get('/index', 'app\controllers\Home@index');

Dynamic Matching Controller Method

The dynamic matching controller method needs to be configured with'dynamicAction'=> true

NOTICE: With the dynamic matching controller method, you should add routing using any(). That is, you cannot qualify the request method REQUEST_METHOD at this time.

// Accessing'/ home/test'will execute'app controllers Home:: test ()'
SRoute::any('/home/(\w+)', app\controllers\Home::class);

// Matching'/home','/home/test', etc.
SRoute::any('/home(/\w+)?', app\controllers\Home::class);

The difference between the two is that the first one does not match / home.

Use Method Actuator

Configure actionExecutor for the method name you need, such as'actionExecutor'=>'run', and all method requests will be submitted to this method.
The real action name is passed as a parameter to run($action), which requires you to schedule in this method to execute the real request method.

It's useful when you need to integrate routers into your own framework

Examples:

// Accessing'/ user', app controllers User:: run ('')
SRoute::get('/user', 'app\controllers\User');

// Accessing'/ user/profile'will call app controllers User:: run ('profile')
SRoute::get('/user/profile', 'app\controllers\User');

// Configure'action Executor'=>'run'and'dynamicAction'=> true at the same time.
// Access'/ user', will call app controllers User:: run ('')
// Access'/user/profile', will call app controllers User:: run ('profile')
SRoute::get('/user(/\w+)?', 'app\controllers\User');

Automatic Matching Routing to Controller

To support automatic matching routing to the controller, just like yii, autoRoute needs to be configured.

    'autoRoute' => [
        'enable' => 1, // Enable
        'controllerNamespace' => 'examples\\controllers', // Namespace where the controller class resides
        'controllerSuffix' => 'Controller', // Controller class suffix
    ],

Match all

Configuration of'matchAll'can be used to intercept all requests. (e.g. when maintaining a website)

Allowed to configure the value of'matchAll'

  • Routing path

    'matchAll' => '/about', // a route path

This route will be executed directly.

  • Callback

    'matchAll' => function () {
        echo 'System Maintaining ... ...';
    },

This callback will be executed directly

Set up event handling (if you need)

SRoute::any('/404', function() {
    echo "Sorry,This page {$_GET['path']} not found.";
});
// Successful matching routing
SRoute::on(SRoute::FOUND, function ($uri, $cb) use ($app) {
    $app->logger->debug("Matched uri path: $uri, setting callback is: " . is_string($cb) ? $cb : get_class($cb));
});

// When the match fails, redirect to'/404'
SRoute::on('notFound', '/404');

// Or, when the matching fails, output the message ___________.
SRoute::on('notFound', function ($uri) {
    echo "the page $uri not found!";
});

Setup configuration (if you need)

// set config
SRoute::config([
    'stopOnMatch' => true,
    'ignoreLastSep' => true,
    'dynamicAction' => true,
    
//    'matchAll' => '/', // a route path
//    'matchAll' => function () {
//        echo 'System Maintaining ... ...';
//    },
    
    // enable autoRoute, work like yii framework
    // you can access '/demo' '/admin/user/info', Don't need to configure any route
    'autoRoute' => [
        'enable' => 1,
        'controllerNamespace' => 'examples\\controllers',
        'controllerSuffix' => 'Controller',
    ],
]);
  • The default configuration is as follows

// All default configurations
[
    // stop on matched. only match one
    'stopOnMatch' => true,
    // Filter the `/favicon.ico` request.
    'filterFavicon' => false,
    // ignore last '/' char. If is True, will clear last '/', so '/home' equals to '/home/'
    'ignoreLastSep' => false,

    // match all request.
    // 1. If is a valid URI path, will match all request uri to the path.
    // 2. If is a callable, will match all request then call it
    'matchAll' => '', // eg: '/site/maintenance' or `function () { echo 'System Maintaining ... ...'; }`

    // auto route match @like yii framework
    'autoRoute' => [
        // If is True, will auto find the handler controller file.
        'enable' => false,
        // The default controllers namespace, is valid when `'enable' = true`
        'controllerNamespace' => '', // eg: 'app\\controllers'
        // controller suffix, is valid when `'enable' = true`
        'controllerSuffix' => '',    // eg: 'Controller'
    ],

    // default action method name
    'defaultAction' => 'index',

    // enable dynamic action.
    // e.g
    // if set True;
    //  SRoute::any('/demo/(\w+)', app\controllers\Demo::class);
    //  you access '/demo/test' will call 'app\controllers\Demo::test()'
    'dynamicAction' => false,

    // action executor. will auto call controller's executor method to run all action.
    // e.g
    //  `run($action)`
    //  SRoute::any('/demo/(:act)', app\controllers\Demo::class);
    //  you access `/demo/test` will call `app\controllers\Demo::run('test')`
    'actionExecutor' => '', // 'run'
]

NOTICE: Some configuration must be done using SRoute::config() before calling SRoute::dispatch().

Start Routing Distribution

SRoute::dispatch();

Running examples

You can run a test server through bash. / php_server, and now you can access it http://127.0.0.1:5670

Project address

Posted by paullb on Thu, 27 Jun 2019 12:25:32 -0700