dannyvankooten /
AltoRouter
PHP routing class. Lightweight yet flexible. Supports REST, dynamic and reversed routing.
88/100 healthLoading repository data…
bramus / repository
A lightweight and simple object oriented PHP Router
A transparent discovery signal based on current public GitHub metadata.
This score does not audit code, security, maintainers, documentation quality, or suitability. Verify the repository and its current documentation before adoption.
A lightweight and simple object oriented PHP Router. Built by Bram(us) Van Damme (https://www.bram.us) and Contributors
GET, POST, PUT, DELETE, OPTIONS, PATCH and HEAD request methodsget(), post(), put(), …X-HTTP-Method-Override headerClass@Method callsInstallation is possible using Composer
composer require bramus/router ~1.6
A demo is included in the demo subfolder. Serve it using your favorite web server, or using PHP 5.4+'s built-in server by executing php -S localhost:8080 on the shell. A .htaccess for use with Apache is included.
Additionally a demo of a mutilingual router is also included. This can be found in the demo-multilang subfolder and can be ran in the same manner as the normal demo.
Create an instance of \Bramus\Router\Router, define some routes onto it, and run it.
// Require composer autoloader
require __DIR__ . '/vendor/autoload.php';
// Create Router instance
$router = new \Bramus\Router\Router();
// Define routes
// ...
// Run it!
$router->run();
Hook routes (a combination of one or more HTTP methods and a pattern) using $router->match(method(s), pattern, function):
$router->match('GET|POST', 'pattern', function() { … });
bramus/router supports GET, POST, PUT, PATCH, DELETE, HEAD (see note), and OPTIONS HTTP request methods. Pass in a single request method, or multiple request methods separated by |.
When a route matches against the current URL (e.g. $_SERVER['REQUEST_URI']), the attached route handling function will be executed. The route handling function must be a callable. Only the first route matched will be handled. When no matching route is found, a 404 handler will be executed.
Shorthands for single request methods are provided:
$router->get('pattern', function() { /* ... */ });
$router->post('pattern', function() { /* ... */ });
$router->put('pattern', function() { /* ... */ });
$router->delete('pattern', function() { /* ... */ });
$router->options('pattern', function() { /* ... */ });
$router->patch('pattern', function() { /* ... */ });
You can use this shorthand for a route that can be accessed using any method:
$router->all('pattern', function() { … });
Note: Routes must be hooked before $router->run(); is being called.
Note: There is no shorthand for match() as bramus/router will internally re-route such requrests to their equivalent GET request, in order to comply with RFC2616 (see note).
Route Patterns can be static or dynamic:
path part of the current URL.A static route pattern is a regular string representing a URI. It will be compared directly against the path part of the current URL.
Examples:
/about/contactUsage Examples:
// This route handling function will only be executed when visiting http(s)://www.example.org/about
$router->get('/about', function() {
echo 'About Page Contents';
});
This type of Route Patterns contain dynamic parts which can vary per request. The varying parts are named subpatterns and are defined using regular expressions.
Examples:
/movies/(\d+)/profile/(\w+)Commonly used PCRE-based subpatterns within Dynamic Route Patterns are:
\d+ = One or more digits (0-9)\w+ = One or more word characters (a-z 0-9 _)[a-z0-9_-]+ = One or more word characters (a-z 0-9 _) and the dash (-).* = Any character (including /), zero or more[^/]+ = Any character but /, one or moreNote: The PHP PCRE Cheat Sheet might come in handy.
The subpatterns defined in Dynamic PCRE-based Route Patterns are converted to parameters which are passed into the route handling function. Prerequisite is that these subpatterns need to be defined as parenthesized subpatterns, which means that they should be wrapped between parens:
// Bad
$router->get('/hello/\w+', function($name) {
echo 'Hello ' . htmlentities($name);
});
// Good
$router->get('/hello/(\w+)', function($name) {
echo 'Hello ' . htmlentities($name);
});
Note: The leading / at the very beginning of a route pattern is not mandatory, but is recommended.
When multiple subpatterns are defined, the resulting route handling parameters are passed into the route handling function in the order they are defined in:
$router->get('/movies/(\d+)/photos/(\d+)', function($movieId, $photoId) {
echo 'Movie #' . $movieId . ', photo #' . $photoId;
});
This type of Route Patterns are the same as Dynamic PCRE-based Route Patterns, but with one difference: they don't use regexes to do the pattern matching but they use the more easy placeholders instead. Placeholders are strings surrounded by curly braces, e.g. {name}. You don't need to add parens around placeholders.
Examples:
/movies/{id}/profile/{username}Placeholders are easier to use than PRCEs, but offer you less control as they internally get translated to a PRCE that matches any character (.*).
$router->get('/movies/{movieId}/photos/{photoId}', function($movieId, $photoId) {
echo 'Movie #' . $movieId . ', photo #' . $photoId;
});
Note: the name of the placeholder does not need to match with the name of the parameter that is passed into the route handling function:
$router->get('/movies/{foo}/photos/{bar}', function($movieId, $photoId) {
echo 'Movie #' . $movieId . ', photo #' . $photoId;
});
Route subpatterns can be made optional by making the subpatterns optional by adding a ? after them. Think of blog URLs in the form of /blog(/year)(/month)(/day)(/slug):
$router->get(
'/blog(/\d+)?(/\d+)?(/\d+)?(/[a-z0-9_-]+)?',
function($year = null, $month = null, $day = null, $slug = null) {
if (!$year) { echo 'Blog overview'; return; }
if (!$month) { echo 'Blog year overview'; return; }
if (!$day) { echo 'Blog month overview'; return; }
if (!$slug) { echo 'Blog day overview'; return; }
echo 'Blogpost ' . htmlentities($slug) . ' detail';
}
);
The code snippet above responds to the URLs /blog, /blog/year, /blog/year/month, /blog/year/month/day, and /blog/year/month/day/slug.
Note: With optional parameters it is important that the leading / of the subpatterns is put inside the subpattern itself. Don't forget to set default values for the optional parameters.
The code snipped above unfortunately also responds to URLs like /blog/foo and states that the overview needs to be shown - which is incorrect. Optional subpatterns can be made successive by extending the parenthesized subpatterns so that they contain the other optional subpatterns: The pattern should resemble /blog(/year(/month(/day(/slug)))) instead of the previous /blog(/year)(/month)(/day)(/slug):
$router->get('/blog(/\d+(/\d+(/\d+(/[a-z0-9_-]+)?)?)?)?', function($year = null, $month = null, $day = null, $slug = null) {
// ...
});
Note: It is highly recommended to always define successive optional parameters.
To make things complete use quantifiers to require the correct amount of numbers in the URL:
$router->get('/blog(/\d{4}(/\d{2}(/\d{2}(/[a-z0-9_-]+)?)?)?)?', function($year = null, $month = null, $day = null, $slug = null) {
// ...
});
Use $router->mount($baseroute, $fn) to mount a collection of routes onto a subroute pattern. The subroute pattern is prefixed onto all following routes defined in the scope. e.g. Mounting a callback $fn onto /movies will prefix /movies onto all following routes.
$router->mount('/movies', function() use ($router) {
// will result in '/movies/'
$router->get('/', function() {
echo 'movies overview';
});
// will result in '/movies/id'
$router->get('/(\d+)', function($id) {
echo 'movie id ' . htmlentities($id);
});
});
Nesting of subroutes is possible, just define a second $router->mount() in the callable that's already contained within a preceding $router->mount().
Class@Method callsWe can route to the class action like so:
$router->get('/(\d+)', '\App\Controllers\User@showProfile');
When a request matches the specified route URI, the showProfile method on the User class will be executed. The defined route parameters will be passed to the class method.
The method can be static (recommended) or non-static (not-recommended). In case of a non-static method, a new instance of the class will be created.
If most/all of your handling classes are in one and the same namespace, you can set the default namespace to use on your router instance via setNamespace()
$router->setNamespace('\App\Controllers');
$router->get('/users/(\d+)', 'User@showProfile');
$router->get('/cars/(\d+)', 'Car@showProfile');
The default 404 handler sets a 404 status code and exits. You can override this default 404 handler by using $router->set404(callable);
$router->set404(function() {
header('HTTP/1.1 404 Not Found');
// ... do something special here
});
You can also define multiple custom routes e.x. you want to define an /api route, you can print a custom 404 page:
$router->set404('/api(/.*)?', function() {
header('HTTP/1.1 404 Not Found');
header('Content-Type: application/json');
$jsonArray = array();
$jsonArray['status'] = "40
Selected from shared topics, language and repository description—not editorial ratings.
dannyvankooten /
PHP routing class. Lightweight yet flexible. Supports REST, dynamic and reversed routing.
88/100 healthxchwarze /
Frieren is a micro-framework designed for use in routers and Single Board Computers (SBCs). This framework is built to be lightweight, efficient, and easy to integrate into various hardware projects.
73/100 healthinhere /
A very lightweight and fast speed PHP request router. 非常快速且轻量的请求匹配路由器。无依赖、简洁、自定义性强,查找匹配速度快
piko-framework /
A lightweight and fast router for PHP
55/100 healthDevAmirul /
A simple, lightweight, and powerful PHP Router with rich features like Middleware and Controllers. Heavily inspired by the way Laravel handles routing.
36/100 healthlizzyman04 /
A lightweight PHP MVC engine with file-based routing and elegant Flow syntax.
76/100 health