PHP code example of hnrazevedo / router

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

    

hnrazevedo / router example snippets


use HnrAzevedo\Router\Route;

/**
 * @param string $uri
 * @param ?array $methods
 * @param ?string $name
 * @param ?string $before
 * @param ?string $after
 * @param ?array $middleware
 * @param ?array $attributes
 * @param ?array $where
 */
#[Route('/path', name:'routeName')]

# Controller File
use HnrAzevedo\Router\Route;

class ControllerAttribute{

    #[Route(
        '/user/{id}',
        methods:['GET'],
        name:'routeName',
        before:'Namespace\Controller@methodBefore',
        middleware:[],
        attributes:[
            'attributeName'=>'attributeValue',
            'attributeName0'=>'attributeValue0'
            ],
        where:['id'=>'[0-9]{1,11}'],
        after:'Namespace\Controller@methodAfter',
    )]
    public function method($param)
    {
        echo 'Controller@method executed!'.PHP_EOL."Param:{$param}";
    }

    public function methodBefore(): void
    {
        echo 'methodBefore'.PHP_EOL;
    }

    public function methodAfter(): void
    {
        echo PHP_EOL.'methodAfter';
    }
}

# Pipeline declaration
use HnrAzevedo\Router\Router;

Router::pipeline([
    HnrAzevedo\Router\Example\Controllers\ControllerAttribute::class,
    'examples\Controllers'
]);

Router::get('/','App\Controller\Application@method');

Router::post('/controller/method','App\Controller\Application@method');

Router::ajax('/userList','foo\bar\User@listme');


Router::globalMiddlewares([
    'Authorization'=> \App\Middlewares\Authorization::class
])

Router::get('/foo','foo\bar\User@method')->middleware([
    \App\Middlewares\Authentication::class,
    'Authorization'
]);

Router::get('/','foo@bar')->name('index');

/**
 * @param string $name
 * @param $value
 */
Router::get('/','foo@bar')->attribute('permission','permissionName');

/**
 * @param string $name
 */
$permission = Router::getAttribute('attributeName');

$permissions = Router::getAttributes();

Router::get('/foo/bar','foo@bar')
      ->before('foo@beforeMethod');

Router::get('/foo/bar','foo@bar')
      ->before(function(){
          //
      });

Router::get('/bar/foo','bar@foo')
      ->after('bar@afterMethod');

Router::get('/bar/foo','bar@foo')
      ->after(function(){
          //
      });

/**
 * @param \Closure|string $action
 * @param ?array $excepts
 */
Router::beforeAll('foo@bar');
Router::beforeAll('foo@bar',['Except_route','Outer_route']);
Router::beforeAll(function(){
          //
      });

/**
 * @param \Closure|string $action
 * @param ?array $excepts
 */
Router::afterAll('bar@foo');
Router::afterAll('bar@foo',['Except_route','Outer_route']);
Router::afterAll(function(){
          //
      });

/**
 * @param string $prefix
 * @param \Closure $definitions
 */
Router::group('/foo', function(){
    Router::post('/bar','foo@bar');
});

/**
 * @param string $name
 * @param $value
 */
Router::group('/foo', function(){
    Router::post('/bar','foo@bar');
})->groupAttribute('permission','permissionName');

/**
 * @param array $middlewares
 * @param ?array $excepts
 */
Router::group('/foo', function(){
    //
})->groupMiddlewares([
    'Authorization'
]);

/**
 * @param \Closure|string $action
 * @param ?array $excepts
 */
Router::group('/foo', function(){
    Router::post('/bar','foo@bar');
})->beforeGroup(function(){
    //
});

/**
 * @param \Closure|string $action
 * @param ?array $excepts
 */
Router::group('/foo', function(){
    Router::post('/bar','foo@bar');
})->afterGroup(function(){
    //
});


Router::delete('pattern','Namespaces\\Controller:method');
Router::get('pattern','Namespaces\\Controller:method');
Router::post('pattern','Namespaces\\Controller:method');
Router::put('pattern','Namespaces\\Controller:method');
Router::patch('pattern','Namespaces\\Controller:method');

Router::get('/{param}', function($param){
    //
});

Router::get('/{param}/{param2}', function($param, $param2){
    //
});

Router::get('/foo/{?id}','foo@bar');

Router::get('/foo/{?any}/{?id}','foo@baz');

Router::get('/user/{?id}/{text}','foo@bat');

Router::get('/test/{id}/{id2}',function(){
    //
})->where([
    'id'=>'[0-9]{1,11}',
    'id2' => '[0-9]*'
]);

Router::group('/bar', function(){
    //
})->groupWhere([
    'id'=>'[0-9]{1,11}',
    'id2' => '[0-9]*'
]);

/* Unique protocol */
Router::get('/get','foo@bar');

/* Multiple protocols */
Router::match('POST|get|AjAx','/my-account','baz@bar');

/* All protocols */
Router::any('/any','all@met');

$route = Router::current();

$name = Router::currentRouteName();

$action = Router::currentRouteAction();

/* NOTE: in case of error an exception is thrown */

/* Load the route via the URL accessed on the Router object */
Router::load();
/* Load the route via the name passed to the Router object */
Router::load('bar');

/* After loading the route it is necessary to fire it */
/* NOTE: After loading the route, if any dispatch function name is passed, it will be ignored. */
Router::load('foo')->run();

Router::load();
$currentRouter = Router::current();
Router::run();

/* NOTE: in case of error an exception is thrown */

/* Trigger route via URL accessed */
Router::run();
/* Trigger route by the given name */
Router::run('baz');

/* Returns the routes already defined for caching */
$routes = Router::routes();
/* Pass cached routes to the router */
Router::routes($routes);

if(!isset($_SESSION['cache']['routes'])){
    //Import routes
    $path = BASEPATH.'/../routes';

    foreach (scandir($path) as $routeFile) {
        if(pathinfo($path.DIRECTORY_SEPARATOR.$routeFile, PATHINFO_EXTENSION) === 'php'){
            ares($_SESSION['cache']['router']['middlewares']);
bash 
"hnrazevedo/router": "^2.4" # PHP <= 7.4
"hnrazevedo/router": "^3.0" # PHP >= 8.0

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
        Options -Indexes
    </IfModule>

    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

    <FilesMatch "index.php">
        allow from all
    </FilesMatch>

</IfModule>