PHP routing class. Lightweight yet flexible. Supports REST, dynamic and reversed routing.

Related tags

Routers php routing
Overview

AltoRouter Build Status Latest Stable Version License Code Climate Test Coverage

AltoRouter is a small but powerful routing class, heavily inspired by klein.php.

$router = new AltoRouter();

// map homepage
$router->map('GET', '/', function() {
    require __DIR__ . '/views/home.php';
});

// dynamic named route
$router->map('GET|POST', '/users/[i:id]/', function($id) {
  $user = .....
  require __DIR__ . '/views/user/details.php';
}, 'user-details');

// echo URL to user-details page for ID 5
echo $router->generate('user-details', ['id' => 5]); // Output: "/users/5"

Features

  • Can be used with all HTTP Methods
  • Dynamic routing with named route parameters
  • Reversed routing
  • Flexible regular expression routing (inspired by Sinatra)
  • Custom regexes

Getting started

You need PHP >= 5.6 to use AltoRouter, although we highly recommend you use an officially supported PHP version that is not EOL.

Contributors

License

MIT License

Copyright (c) 2012 Danny van Kooten [email protected]

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Comments
  • [SOLVED]Undefined offset: 1  while using AltoRouter

    [SOLVED]Undefined offset: 1 while using AltoRouter

    Everything was working fine until today. Now I'm getting this error Undefined offset: 1 and error is pointed to this line of code list($controller,$method)=explode("@",$match['target']);

    Here is the whole code from index.php :

    <?php
         include(__DIR__.'/../bootstrap/start.php');
    Dotenv::load(__DIR__."/../"); 
    include(__DIR__.'/../bootstrap/db.php');
    include(__DIR__."/../routes.php");
    
     $match=$router->match();
    
     list($controller,$method)=explode("@",$match['target']);
    
     if(is_callable(array($controller,$method))){
            $object=new $controller();
            call_user_func_array(array($object,$method), array($match['params']));
     }else{
    
        echo "Can not find $controller->$method";
        exit();
     }
    
    opened by pivnicki 26
  • Language regex

    Language regex

    Hello i want to match this url

    http://localhost/en_US

    the map is $router->map('GET', '/[a:lang]/?', '', 'language');

    the country code regex is [A-Za-z]{2}_[A-Za-z]{2}

    it is possible to work this?

    opened by nikmauro 23
  • External file for routes

    External file for routes

    Hi,

    Is possible add external file (example .ini file) with all routes, something like:

    [routes] home="GET|POST /home home#index" users="GET /users users#index"

    then when we create new instance we can:

    $router = new AltoRouter('routes.ini');

    $match = $router->match();

    Thanks!!

    opened by kamov 20
  • Uploading a file

    Uploading a file

    Hi, it's me again. Trying to upload a file with a form like this:

    <form action='/admin/' method='post' enctype='multipart/form-data'>
    	<input type='file' name='file' id='file'/>
    	<input type='submit' value='upload'> 	
    </form>
    ```
    i have such path written 
    $router->map('POST','/admin/', 'class/admin.php', 'edited');
    but when i try to catch the file with this code
    if($_POST){
    			print_r($_FILES);
    	}
    nothing happens
    Thx
    opened by WingRS 15
  • example for actually calling controller#action and passing vars?

    example for actually calling controller#action and passing vars?

    hi there, just played a bit with AltoRouter and figured out that it leaves out to me to actually call the matched controller#action and pass the appropriate vars but i am not sure i implemented this correctly. it surely works but thought of making sure i am on the correct route :) you might want to include this in an example if this is the correct way of doing this to help others

    $router = new AltoRouter();
    $router->setBasePath('/demosite4.com'); 
    $router->map('GET','/', 'home_controller#display_item', 'home');
    $router->map('GET','/content/[:parent]/?[:child]?', 'content_controller#display_item', 'content');
    $match = $router->match();
    
    // not sure if code after this comment  is the best way to handle matched routes
    list( $controller, $action ) = explode( '#', $match['target'] );
    if ( is_callable(array($controller, $action)) ) {
        $obj = new $controller();
        call_user_func_array(array($obj,$action), array($match['params']));
    } else if ($match['target']==''){
        echo 'Error: no route was matched'; 
        //possibly throw a 404 error
    } else {
        echo 'Error: can not call '.$controller.'#'.$action; 
        //possibly throw a 404 error
    }
    
    
    // content_controller class file is autoloaded 
     <?php
    class content_controller {
        public function display_item($args) {
            //echo our params to to make sure we got them
            echo 'parent: '. $args['parent'];
            echo 'child: '. $args['child'];
        }
    ?>
    
    opened by unitedworx 15
  • How To Pass 2 Parameters WIthout Having Class

    How To Pass 2 Parameters WIthout Having Class

    Hello, i have successfully implementing simple one query: $router->map('GET|POST', '/login/', 'module/user/login.php', 'login'); turn into : http://mydomain/login/

    but when I have 2 GET parameters it not successfully passed, error said: Catchable fatal error: Object of class Closure could not be converted

    my map: $router->map( 'GET', '/email/[*:getemail]/key/[*:getkey]/', 'module/user/activate.php', 'activate');

    activate.php:

    $email = filter_var($_GET["email"], FILTER_SANITIZE_EMAIL);
    $key = htmlspecialchars($_GET["key"]);
    $getemail = $match['params'][$email];
    $getkey = $match['params'][$key];
    
    // and more... code for validation
    

    my expectation is: http://mydomain/email/user@email/key/user_key/

    Thank you for your help.

    question 
    opened by asisten 14
  • Altorouter search to match all external files (JS, img, ...)

    Altorouter search to match all external files (JS, img, ...)

    Hello, I have a problem with Altorouter. I established routes and attached my views. In my views, I have images but they do not display because when the image tries to load, my index.php (where there are routes, the match() method, etc.) tries to match the url of the image to a mapped route...

    There is possibility to make an exception for images / js scripts?

    I hope you can help me :)

    Thank you!

    opened by ghost 13
  • Performance improvement: Radix-ish tree for HTTP methods

    Performance improvement: Radix-ish tree for HTTP methods

    To speed up route matching it might make sense to move to a Radix tree-ish approach. While a full blown Radix tree is probably not suited for PHP unless we write to a file somewhere, a quick & easy win might be to split up the AltoRouter::$routes array into separate keys for each HTTP method.

    This way, we do not have to loop through routes and compare the HTTP method which should slightly speed up the match process, especially for non-existing routes or routes other than the most commonly used GET.

    Cons

    • getRoutes() currently exposes the internal routes array, so this would most likely mean a BC break. Not sure if that's even worth the potential gain.
    • AltoRouter accepts multiple HTTP methods, which means possibly storing a route more than once. We already do this for the $namedRoutes array though and PHP uses copy-on-write, so this should not be an issue really.
    enhancement 
    opened by dannyvankooten 12
  • There is some way to ignore a route?

    There is some way to ignore a route?

    I have the following structure:

    . project .. src .... controllers .... models .... views ...... layouts .. public .... js .... css

    Everytime i try to load a css or js, it matches them routes and redirect to my 404 file... can i ignore the public path on routes??

    question 
    opened by franklinrabay 12
  • addition of examples

    addition of examples

    1. example to process matched route by calling controller->method and passing params as a named array so params can be accessed by their name inside the method we called
    2. example to load routes from an external yaml file

    These were tested to be workign on a local setup

    Signed-off-by: Paris Paraskeva [email protected]

    opened by unitedworx 12
  • URL Request isn't absolute

    URL Request isn't absolute

    When creating a URL request, it doesn't take your complete URL as the request. It gets matches from the URL in the order that they are mapped.

    For example, if i have /login/ mapped to login.php and /home/ mapped to home.php (in that order), so: site.com/login/ shows login.php site.com/home/ shows home.php site.com/home/login/ shows login.php (since it's mapped first) site.com/gibberish/randomstuff/home shows home.php (even though gibberish and randomstuff isn't mapped at all, so it should throw an error.) but then: site.com/gibberish/randomstuff/login/home will show login.php (because its mapped first, even though home was the last one on the URL)

    Just wanting to work out a way to fix this problem

    Thanks!!

    opened by un-matthewdavis 11
  • i don't understand route width paging

    i don't understand route width paging

    Hello,

    i just found out about your router and how do you deal with the router with forum paging as i get the id get answers from the topic and i don't understand this is redirecting me to another topic

    thank you

    my route

    $router->map('GET|POST', '/forum/viewtopic-[*:slug]-[i:id]', 'viewtopic','viewtopic'); //no paging
    $router->map('GET|POST', '/forum/viewtopic-page-[*:slug]-[i:id]-[i:paginat]', 'viewtopic','viewtopic-page');
    

    the route is not decomposed with the parameters

    normally i should have this

    titre-de-mon-topic-edite slug 1 id 3 page viewtopic-page name

    but i am getting this

    page-titre-de-mon-topic-edite-1 slug

    array (size=3)
      'target' => string 'viewtopic' (length=9)
      'params' => 
        array (size=2)
          'slug' => string 'page-titre-de-mon-topic-edite-1' (length=31) 
          'id' => string '2' (length=1)
      'name' => string 'viewtopic' (length=9) 
    

    translated by Google !

    opened by neecride 0
  • Multilingue

    Multilingue

    Hello,

    I would create multilingual routes but I don't know how.

    There is the flag [:lang] but then we are forced to have untranslated routes

    domain.tld/en/my-home-page
    domain.tld/fr/my-home-page
    

    I would like to have :

    domain.tld/en/my-home-page
    domain.tld/fr/ma-page-d-accueil
    

    How do I do it? create several similar routes?

    ->get('/en/my-home-page', 'home', 'home-en')
    ->get('/fr/ma-page-d-accueil', 'home', 'home-fr')
    

    Thank you

    opened by kevinpeuman 0
  • Leftover params label:enhancement

    Leftover params label:enhancement

    It would be cool if on ->generate() params which was not used are added to as query string

    public function generate($routeName, array $params = array()) {
    	
    	// Check if named route exists
    	if(!isset($this->namedRoutes[$routeName])) {
    		throw new \Exception("Route '{$routeName}' does not exist.");
    	}
    	
    	// Replace named parameters
    	$route = $this->namedRoutes[$routeName];
    	
    	// prepend base path to route url again
    	$url = $this->basePath . $route;
    	
    	if (preg_match_all('`(/|\.|)\[([^:\]]*+)(?::([^:\]]*+))?\](\?|)`', $route, $matches, PREG_SET_ORDER)) {
    		
    		foreach($matches as $match) {
    			list($block, $pre, $type, $param, $optional) = $match;
    			
    			if ($pre) {
    				$block = substr($block, 1);
    			}
    			
    			if(isset($params[$param])) {
    				$url = str_replace($block, $params[$param], $url);
    				unset($params[$param]);//set param as used
    			} elseif ($optional) {
    				$url = str_replace($pre . $block, '', $url);
    			}
    		}
    	}
    	
    	if (count($params) > 0) //check is any params left to build url with
    	{
    		$url .= '?'.http_build_query($params);
    	}
    	
    	return $url;
    }
    

    then

    $alto->map( 'GET|POST', '/users/[i:id]/','handleContactForm');
    $alto->generate('handleContactForm',['id'=>10,'myCustomParam'=>'blaah']);
    // will outputs /users/10?myCustomParam=blaah
    
    opened by infira 0
  • Map function does not work on Xampp

    Map function does not work on Xampp

    Hello OS: windows

    i put my website in htdocs root directory. when i do this code it cannot load index.php from views directory without any error.

    include ('router/AltoRouter.php');
    $router = new AltoRouter();
    $router->map( 'GET', '/', function() {
       require (__DIR__ . '/views/index.php');
    },"home");
    

    project structure:

    • router : alto files
    • views
      • index.php
    • .htaccess => rewite works (i checked)
    • index.php => rewite works (i checked)

    urls i checked:

    • http://127.0.0.1
    • http://127.0.0.1/

    also

    • i added echo 'done' to $router->map but nothing happened
    • i followed getting started articles.
    opened by ejamshidiasl 1
  • Example of controller

    Example of controller

    Hello.

    Can you give an example code of a controller that accepts parameter?

    For instance an ArticleController that has 3 functions: getArticle($id) and updateArticle($id, $newTitle)

    opened by thierryler 1
Releases(2.0.2)
  • 2.0(Nov 10, 2019)

  • v1.2.0(May 8, 2016)

    Added getRoutes to retrieve a full route mapping (#97)

    $router = new AltoRouter()
    $router->addRoutes(array(
        array('GET', '/login', 'show_login_action', 'show_login'),
        array('POST', '/login', 'do_login_action', 'do_login'),
        array('DELETE', '/logout', 'do_logout_action', 'do_logout'),
    ));
    $routes = $router->getRoutes();
    var_export($routes);
    

    Will output:

    array (
      0 =>
      array (
        0 => 'GET',
        1 => '/login',
        2 => 'show_login_action',
        3 => 'show_login',
      ),
      1 =>
      array (
        0 => 'POST',
        1 => '/login',
        2 => 'do_login_action',
        3 => 'do_login',
      ),
      2 =>
      array (
        0 => 'DELETE',
        1 => '/logout',
        2 => 'do_logout_action',
        3 => 'do_logout',
      ),
    )
    

    Furthermore does this release concerns documentation changes.

    View all changes since v1.1.0.

    Source code(tar.gz)
    Source code(zip)
  • v1.1.0(Apr 17, 2014)

    Added addRoutes method for bulk adding routes (#68):

    $router = new AltoRouter();
    $router->addRoutes(array(
        array('GET', '/login', 'show_login_action', 'show_login'),
        array('POST', '/login', 'do_login_action', 'do_login'),
        array('DELETE', '/logout', 'do_logout_action', 'do_logout'),
    ));
    

    AltoRouter now supports unicode regular expressions (#69).

    View all changes since v1.0.1.

    NB. Following Semver; this is now v1.1.0 instead of v1.0.2

    Source code(tar.gz)
    Source code(zip)
  • v1.0.1(Jan 23, 2014)

    Added support for custom match types:

    $router = new AltoRouter();
    $router->addMatchTypes(array('cId' => '[a-zA-Z]{2}[0-9](?:_[0-9]++)?'));
    
    $router->map('GET', '/users/[cId:id]', 'customers#show', 'customers_show');
    

    Fixed some bugs:

    • #38 #20 When a basePath is set, the custom route is not being checked against because the first character is not an @. (Fixed in 01258d15ef96fc7537fd904f53ffa621ab58ddc1)
    • #22 A . was not seen as path separator for optional parts. (Fixed in #35)

    View all changes since v1.0.0.

    Source code(tar.gz)
    Source code(zip)
Owner
Danny van Kooten
Independent developer, writing open-source code for a living.
Danny van Kooten
Routing - The Routing component maps an HTTP request to a set of configuration variables.

Routing Component The Routing component maps an HTTP request to a set of configuration variables. Getting Started $ composer require symfony/routing

Symfony 7.3k Jan 6, 2023
PHPRouter is an easy-to-use, fast, and flexible PHP router package with express-style routing.

PHP-Router is a modern, fast, and adaptable composer package that provides express-style routing in PHP without a framework.

Ayodeji O. 4 Oct 20, 2022
PHP Router class - A simple Rails inspired PHP router class.

PHP Router class A simple Rails inspired PHP router class. Usage of different HTTP Methods REST / Resourceful routing Reversed routing using named rou

Danny van Kooten 565 Jan 8, 2023
Simple, fast and yet powerful PHP router that is easy to get integrated and in any project.

Simple, fast and yet powerful PHP router that is easy to get integrated and in any project. Heavily inspired by the way Laravel handles routing, with both simplicity and expand-ability in mind.

Simon Sessingø 472 Jan 4, 2023
Simple and minimal yet another PHP 7 Framework

DemirApp Minimal PHP Framework Introduction Simple and minimal yet another PHP 7 Framework Features Simple routing Simple container (Dependency Inject

yidemir 12 Sep 19, 2022
Fast PSR-7 based routing and dispatch component including PSR-15 middleware, built on top of FastRoute.

Route This package is compliant with PSR-1, PSR-2, PSR-4, PSR-7, PSR-11 and PSR-15. If you notice compliance oversights, please send a patch via pull

The League of Extraordinary Packages 608 Dec 30, 2022
🔍 This is a collection of utilities for routing and loading components.

Router Utilities - PHP Introduction A day will come when I will write documentation for this library. Until then, you can use this library to create r

Utilities for PHP 5 Sep 20, 2022
Generate a PHP script for faster routing :rocket:

SwitchRoute Generating a PHP script for faster routing. The traditional way of routing uses regular expressions. This method was improved by FastRoute

Arnold Daniels 75 Nov 20, 2022
Convention based routing for PHP

Croute Convention based routing for PHP based on Symfony components. Croute is great because: You don't need to maintain a routing table Promotes cons

Michael O'Connell 12 Nov 9, 2021
Flight routing is a simple, fast PHP router that is easy to get integrated with other routers.

The PHP HTTP Flight Router divineniiquaye/flight-routing is a HTTP router for PHP 7.1+ based on PSR-7 and PSR-15 with support for annotations, created

Divine Niiquaye Ibok 16 Nov 1, 2022
Ertuo: quick routing for PHP

Ertuo: quick routing for PHP Ertuo (anagram of "Route"), is a small PHP library that does routing better and faster than conventional regular expressi

Ertuo 29 Jul 19, 2022
klein.php is a fast & flexible router for PHP 5.3+

Klein.php klein.php is a fast & flexible router for PHP 5.3+ Flexible regular expression routing (inspired by Sinatra) A set of boilerplate methods fo

null 2.6k Jan 7, 2023
A fast & flexible router

Klein.php klein.php is a fast & flexible router for PHP 5.3+ Flexible regular expression routing (inspired by Sinatra) A set of boilerplate methods fo

null 2.6k Dec 28, 2022
A lightweight and simple object oriented PHP Router

bramus/router A lightweight and simple object oriented PHP Router. Built by Bram(us) Van Damme (https://www.bram.us) and Contributors Features Support

Bramus! 935 Jan 1, 2023
PhpRouter is a powerful, lightweight, and very fast HTTP URL router for PHP projects.

PhpRouter PhpRouter is a powerful, lightweight, and very fast HTTP URL router for PHP projects. Some of the provided features: Route parameters Predef

Milad Rahimi 152 Dec 28, 2022
A lightweight and fast router for PHP

Piko Router A lightweight and blazing fast router (see benchmarks) using a radix trie to store dynamic routes. This router maps routes to user defined

Piko framework 62 Dec 27, 2022
A lightweight and very basic PHP router.

Katya A lightweight PHP router Configuration Para servidor Apache, en el directorio del proyecto crea y edita un archivo .htaccess con lo siguiente: <

Luis RodrĂ­guez 0 Apr 4, 2022
:tada: Release 2.0 is released! Very fast HTTP router for PHP 7.1+ (incl. PHP8 with attributes) based on PSR-7 and PSR-15 with support for annotations and OpenApi (Swagger)

HTTP router for PHP 7.1+ (incl. PHP 8 with attributes) based on PSR-7 and PSR-15 with support for annotations and OpenApi (Swagger) Installation compo

Sunrise // PHP 151 Jan 5, 2023
Pux is a fast PHP Router and includes out-of-box controller tools

Pux Pux is a faster PHP router, it also includes out-of-box controller helpers. 2.0.x Branch Build Status (This branch is under development) Benchmark

Yo-An Lin 1.3k Dec 21, 2022