patrikmokry / router
A fast PHP router, with route parameters
dev-master
2019-01-27 13:43 UTC
Requires
- php: ^7
This package is auto-updated.
Last update: 2025-03-28 02:54:07 UTC
README
A lightweight and simple object oriented PHP Router with support of Controllers.
This library provides a fast implementation of a regular expression based router.
Easy to install with composer
Install via composer
composer require patrikmokry/router
Usage
Example
// index.php use PatrikMokry\Router; require_once __DIR__ . '/vendor/autoload.php'; Router::get('example', function() { return 'This route responds to requests with the GET method at the path /example'; }); Router::get('example/{id}', function($id) { return 'This route responds to requests with the GET method at the path /example/<anything>'; }); Router::get('example/{id}?', function() { return 'This route responds to requests with the GET method at the path /example/[optional]'; }); Router::post('example', function() { return 'This route responds to requests with the POST method at the path /example'; }); Router::execute(__DIR__);
// .htaccess RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-l RewriteRule ^(.+)$ index.php [QSA,L]
Defining Routes
use PatrikMokry\Router; Router::get($route, $action); Router::post($route, $action); Router::put($route, $action); Router::delete($route, $action); Router::any($route, $action);
These helper methods are wrappers around
route($route, $action, $method = ["POST", "GET"])
Neither$_PUT
nor$_DELETE
does not exist so in your request you must define field with name_method
Regex Shortcuts
:i => (\d+) # numbers only
:s => (\w+) # any word, character
use in routes:
'/user/{name::i}'
'/user/{name::s}'
Custom shortcuts
Router::addShortcut(name, regex) // create shortcut with default value Router::addShortcut('locale', '(sk|en)->sk)')
Named Routes for Reverse Routing
Router::get('example/{id}', function() { return 'example'; })->name('example'); echo Router::link('example', ['id' => 48]) // example/48
Prefix Groups
// If you need some prefix e.g. admin, api, locale, ... Router::prefix('admin/', function() { Router::get('example/{id}', function() { return 'example'; }); });
Contributing
- Fork it ( https://github.com/MokryPatrik/PHP-Router/fork )
- Create your feature branch (git checkout -b my-new-feature)
- Commit your changes (git commit -am 'Add some feature')
- Push to the branch (git push origin my-new-feature)
- Create a new Pull Request