admirhodzic/nano-router

Nano router for PHP apps

1.0.0 2019-11-01 07:50 UTC

This package is auto-updated.

Last update: 2024-10-06 20:47:50 UTC


README

Nano-size router for PHP apps in just 20 lines of code.

Install

composer require admirhodzic/nano-router

Usage

use admirhodzic\NanoRouter\NanoRouter;
// ...
$response = NanoRouter::run([
                //options...
            ]);

When request URL is /posts/update/123?param2=abc, this code will invoke a class with name PostController and call method actionUpdate with $id parameter set to '123' and 'param2' set to 'abc', if param2 is not set, default value is used. "id" parameter is mandatory.

class PostController{
    public action actionUpdate($id, $param2=''){ ... }
}

If URL doesn't contain controller or action name, defaults will be used. By default, 'SiteController' and 'actionIndex' method. To specify separate methods for different HTTP methods, just add a function with method name instead of 'action':

public function getPosts() { ... } 
public function postPosts() { ... }
public function actionPosts() { ... }

This way, for GET request, 'getPosts' function will be called, for POST request, 'postPosts' function will be called, and 'actionPosts' will be called for all other request methods.

Options

'default_controller'=>'site',
'default_action'=>'index',
'Controller'=>'Controller', //suffix of controller class name
'controller_namespace'=>'app\Controllers',
'routes'=>[
    //...custom routes. eg:
    
    '/login'=>'site/login', 
    
    ///////////////       value is new URI string or a function which receives preg matches and returns a string

    'r1/a1(/(?<id>[0-9]*))?'=>function ($p) {  ///////////// this matches r1/ar with optional numeric id
            //function receives extracted parameters and returns new <controller>/<action>/<id> URI
            return isset($p['id']) ? ('site/other/'.$p['id']) : 'site/index'; 
        },
    
    ///////////////       routes order must be from most specific to general routes
]

License

MIT