PHP Router class - A simple Rails inspired PHP router class.

Related tags

Routers PHP-Router
Overview

PHP Router class

Latest Stable Version Total Downloads Latest Unstable Version License

A simple Rails inspired PHP router class.

  • Usage of different HTTP Methods
  • REST / Resourceful routing
  • Reversed routing using named routes
  • Dynamic URL's: use URL segments as parameters.

Authors

Easy to install with composer

$ composer require dannyvankooten/php-router

Usage

Friendly URL

Create a simple .htaccess file on your root directory if you're using Apache with mod_rewrite enabled.

Options +FollowSymLinks
RewriteEngine On
RewriteRule ^(.*)$ index.php [NC,L]

If you're using nginx, setup your server section as following:

server {
	listen 80;
	server_name mydevsite.dev;
	root /var/www/mydevsite/public;

	index index.php;

	location / {
		try_files $uri $uri/ /index.php?$query_string;
	}

	location ~ \.php$ {
		fastcgi_split_path_info ^(.+\.php)(/.+)$;
		# NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini

		# With php5-fpm:
		fastcgi_pass unix:/var/run/php5-fpm.sock;
		fastcgi_index index.php;
		include fastcgi.conf;
		fastcgi_intercept_errors on;
	}
}

This is a simple example of routers in action


require __DIR__.'/vendor/autoload.php';

use PHPRouter\RouteCollection;
use PHPRouter\Router;
use PHPRouter\Route;

$collection = new RouteCollection();
$collection->attachRoute(new Route('/users/', array(
    '_controller' => 'someController::usersCreate',
    'methods' => 'GET'
)));

$collection->attachRoute(new Route('/', array(
    '_controller' => 'someController::indexAction',
    'methods' => 'GET'
)));

$router = new Router($collection);
$router->setBasePath('/PHP-Router');
$route = $router->matchCurrentRequest();

var_dump($route);

Load routers from a yaml file

We can define in a yaml file all the routes of our application. This facilitates our life when we need to migrate, modify, or later add new routes.

The route definition should follow the example below:

base_path: /blog

routes:
  index: [/index, someClass.indexAction, GET]
  contact: [/contact, someClass.contactAction, GET]
  about: [/about, someClass.aboutAction, GET]

In our Front Controller would have something like:


require __DIR__.'/vendor/autoload.php';

use PHPRouter\RouteCollection;
use PHPRouter\Config;
use PHPRouter\Router;
use PHPRouter\Route;

$config = Config::loadFromFile(__DIR__.'/router.yaml');
$router = Router::parseConfig($config);
$router->matchCurrentRequest();

More information

If you like PHP Router you might also like AltoRouter.

License

MIT Licensed, http://www.opensource.org/licenses/MIT

Comments
  • How to get parameters properly / regex patterns not working ?

    How to get parameters properly / regex patterns not working ?

    In 1.1Alpha i use this:

    $collection->attachRoute(new PHPRouter\Route('/sitemap/info.xml', [
        '_controller' => 'App\Controllers\Sitemap::Sitemap',
        'methods' => ['POST','GET'],
        'parameters'=> ['template_file'=>'ajax'],
    ]));
    

    and get_object_vars($route)['_config']['parameters']['template_file'] to get "ajax" value, but now in last version this not working.

    How to make something like this ?

    opened by agregator123 19
  • php router vs alto router

    php router vs alto router

    hi,

    i just found this ... another router class .... I start already play with AltoRouter, which work fine, can you explain the difference between phprouter-altorouter?

    Thanks

    opened by kamov 16
  • Regex and passing values

    Regex and passing values

    • PHPRouter version: dev-master
    • PHP version: 7.2

    Hi, I'm currently facing a small challenge where I didn't found any solution for in the README or the Issues.

    I want to have this: Access /id/1 and I want to pass the 1 over to the Controller. I've tried many things and am stuck on this for 3 hours now. Help is much apprecicated!

    This is my current code (reset everything):

    <?php
    require("vendor/autoload.php");
    
    use Angle\Engine\Router\Collection;
    use Angle\Engine\Router\Route;
    use Angle\Engine\Router\Router;
    use \Angle\Engine\Template\Engine;
    
    use Tracy\Debugger;
    
    Debugger::enable();
    
    define("MYSQL_HOST", "localhost");
    define("MYSQL_USER", "bennet");
    define("MYSQL_PASSWORD", "root");
    define("MYSQL_DATABASE", "bennet");
    
    $collection = new Collection();
    
    $engine = new Engine();
    
    $collection->attach(new Route("/", array(
        "_controller" => '\Blog\Controllers\Overview::display',
        "parameters" => ["engine" => $engine],
        "methods" => 'GET'
    )));
    
    // id url
    $collection->attachRoute(new Route("/id/:id", array(
        "_controller" => '\Blog\Controllers\Overview::display',
        "parameters" => ["engine" => $engine],
        "methods" => 'GET'
    )));
    
    
    $router = new Router($collection);
    $router->matchCurrentRequest();
    
    bug 
    opened by bennetgallein 8
  • Regex not taking encoded URI strings as parameter in consideration

    Regex not taking encoded URI strings as parameter in consideration

    URI's like this:

    http://example.com/account/authenticate/facebook/http%3A%2F%2Fexample.com%2Fpub%2Flogin%2Fadmin%2F%23!%2F

    Is not accepted by the regex..

    $router->map('/account/authenticate/:external_auth_vendor/:location', array('controller' => 'PageController', 'action' => 'external_auth'), array('methods' => 'GET', 'name' => 'account_login_external'));  
    
    opened by phun-ky 7
  • Variable paths can override static paths

    Variable paths can override static paths

    Ran into this today,

    I was adding routes like so:

    thing/:handle (just GET) thing/update (GET and POST)

    as you can see the one with the variable is there first,

    I would request thing/update so when the router filters through the routes it hits thing/:handle and stops because it matches, the only way around this is to add thing/update before thing/:handle,

    if there was a way to sort it by ones that do not have variables (static routes) that would be awesome

    opened by Mnkras 7
  • Custom parameters passing

    Custom parameters passing

    • PHPRouter version: 1.2alpha
    • PHP version 8.1

    Hi again, guys :)

    I started a topic in stackoverflow for my previous problem and there is some replies: https://stackoverflow.com/questions/71241075/php-8-unknown-named-parameter-dannyvankooten-router/71241345?noredirect=1#comment125927353_71241345

    They told me to remove this line from code: 'parameters'=> ['template_file'=>'ajax'],

    to my script start working, but this is so important ... I started this one to give a suggestion to making edit in router code to start working like this :)

    This is important, because i use template engine mustache and i pass the variables like this: $tpl = $mustache->loadTemplate(get_object_vars($route)['_config']['parameters']['template_file']);

    and this: $tpl = $mustache->loadTemplate($route->getParameters()['template_file']);

    both working in php 5.4> and <php7.4

    Without this ones i'm lost and my CMS can't working... This is very important... Its so easy to set a template file in routes and to catch this one from my template system... It's very clear and pleasant way.. If you help me to start this working i will be very happy :)

    Thanks in advance.

    opened by Pok4 6
  • Its possible to access more than one method from router ?

    Its possible to access more than one method from router ?

    • PHPRouter version: 1.2alpha
    • PHP version 7.4

    Hello guys, i have a question about the routers, this one: '_controller' => 'App\Controllers\BaseController::__construct', works.

    but this one: '_controller' => 'App\Controllers\BaseController::__construct::the_tickets::ajax', not works...

    i check in base controller with class_exists('the_tickets') and it shows true... My question is about can i access more than one method in routing... Thank you for any replies.. :)

    opened by Pok4 6
  • Load config as Json Or Yaml to avoid Yaml dependencies

    Load config as Json Or Yaml to avoid Yaml dependencies

    Hi,

    I like this package because it's a very simple Router. To keep this project very simple and independent, I think it would be nice to allow configs to be in Yaml OR Json format, to avoid the Yaml library dependency. Yaml mode could also use the php native methods when available ( http://php.net/manual/fr/book.yaml.php )

    The objective is to avoid avoidable dependencies.

    Have a good day

    feature enhancement 
    opened by lpotherat 6
  • Routing by yaml-File not work correct ?

    Routing by yaml-File not work correct ?

    Hi!

    I use the following (test) Routingfile:

    -- CUT HERE base_path: /api

    routes: ping: [/ping, \Myuniquename\Api\Test.ping, GET] -- CUT HERE

    When i call my "frontcontroller" i get:

    -- index.php

    $routes = Config::loadFromFile($basePath . '/config/routes.yaml');

    Array (size=2) 'base_path' => string '/api' (length=4) 'routes' => array (size=1) 'ping' => array (size=3) 0 => string '/ping' (length=5) 1 => string '\Myuniquename\Api\Test.ping' (length=27) 2 => string 'GET' (length=3)

    $router = Router::parseConfig($routes);

    Object(PHPRouter\Router)[35] private '_routes' => object(PHPRouter\RouteCollection)[33] private '_namedRoutes' => array (size=0) empty private '_basePath' => string '' (length=0)

    // Look above: the basepath is empty, But i set it in routes.yaml.

    So this will not work (but should because of base_path):

     http://www.foo.bar/api/ping
    

    but this will work (but should not):

     http://www.foo.bar/ping
    

    But i set "base_path" in yaml-File (as described in README).

    Maybe my mistake ?

    CU, Kai.

    bug 
    opened by kaiszy 6
  • Add callback before dispatch

    Add callback before dispatch

    As an enhancement, it could be useful to have a "shouldDispatchCallback".

    • Router class have a setShouldDispatchCallback method
    • Just before the call to $routes->dispatch(), the router calls the callback, if callback return false, route is ignored, else the callback returns the route.

    => it can be used to allow / disallow access to routes

    opened by lpotherat 5
  • Set filter, regex are not used?

    Set filter, regex are not used?

    Hi,

    i have a problem with setFilters, when i'm going on http://dn.tld/js/library.js all work fine, but when i'm trying to access http://dn.tld/js/library.min.js $router->matchCurrentRequest(); return false, this is really weird.

    $routes[++$i] = new Route('/js/:filename.js', ['_controller' => 'App\Controller\Misc\Minify::JS', 'methods' => 'GET']);
    $routes[$i]->setFilters([':filename' => '([[:alnum:]\.]+)'], true);
    

    I have tried with POSIX, Ascii and Unicode expression and i have the same problem with all of them, the router seem match only the default regex.

    bug 
    opened by antoine-pous 5
  • Controller method with custom params (ids parameters excluded) throw  Too few arguments Exception

    Controller method with custom params (ids parameters excluded) throw Too few arguments Exception

    • PHPRouter version: @dev-master
    • PHP version:
    • Exact steps to cause this issue
      1. Create abstraction of router.
      2. Create controllers with customs params and at first the id, and load routes.
      3. Sending request.
    • What you expected
      • e.g. I expected to get my custom params with the id.
    • What happened instead
      • e.g. Instead, I got Error : Too few arguments to function Controller::test(), 1 passed and exactly 2.

    Hey ! just found an exception about controllers method params. I wanted to pass (with or without url dynamic param) some custom object like a RequestObject.

    To fix it, in Router.php, match() function, just before call $routes->setParameters($params);, add

    foreach ($routes->getParameters() as $parameter) {
               $params[] = $parameter;
    }
    

    Thanks you.

    opened by brodalee 0
  • Added shouldDispatchCallback

    Added shouldDispatchCallback

    It is a very simple and naive implementation actually not PSR-15 compliant, but maybe it is a good start for PSR-15 compliance.

    The idea is to set a callback before dispatching the route, with these rules :

    • The callback take one parameter which is the Route to be dispatched
    • if the callback returns false or equivalent, the route is ignored and the router continues to check other routes.
    • if the callback returns a route, it is dispatched. So you can simply return the route to allow it, or generate a new Route in replacement (like an Error route for example).
    opened by lpotherat 0
  • Skip dispatch after match

    Skip dispatch after match

    • PHPRouter version: 1.2.0-alpha
    • PHP version: PHP 7.1:
    • Exact steps to cause this issue
      1. I configured RouteCollection
      2. I run method matchCurrentRequest on Router
    • What you expected
      • I expected to get all information about route and use this information in other middleware using psr 15
    • What happened instead
      • Router create controller object and run the action

    Is it possible to turn of run method dispatch() after find route by configuration flag.

    enhancement 
    opened by fitdev-pro 4
  • Method request

    Method request

    I want to submit a nice request ( i think ) For now in methods we have: GET POST etc... i want to be added one more "XHR" or "Ajax" and this one can be accepted only ajax requests. Now my controllers with ajax must be like this:

     if(parent::is_ajax()) {
     //my code
    }
    
    

    is_ajax function is:

      public function is_ajax() {
        return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
      }
    

    I need this to be added and my routers will be:

    $collection->attachRoute(new PHPRouter\Route('/', [
        '_controller' => 'App\Controllers\Index::Index',
        'methods' => 'AJAX',
        'parameters'=> ['template_file'=>'index'],
    ]));
    

    instead

    $collection->attachRoute(new PHPRouter\Route('/', [
        '_controller' => 'App\Controllers\Index::Index',
        'methods' => 'GET',
        'parameters'=> ['template_file'=>'index'],
    ]));
    

    is this possible ?

    feature enhancement 
    opened by agregator123 2
Releases(1.2.0-alpha)
Owner
Danny van Kooten
Independent developer, writing open-source code for a living.
Danny van Kooten
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
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
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
A simple PHP Router

Panda Router Description the panda-router is a small alternative PHP router that can be used for small projects. With this router you can use differen

Jan Behrens 1 Dec 27, 2021
The simple PHP router

Macaw Macaw is a simple, open source PHP router. It's super small (~150 LOC), fast, and has some great annotated source code. This class allows you to

Noah Buscher 895 Dec 21, 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
Fast request router for PHP

FastRoute - Fast request router for PHP This library provides a fast implementation of a regular expression based router. Blog post explaining how the

Nikita Popov 4.7k Dec 23, 2022
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
A web router implementation for PHP.

Aura.Router Powerful, flexible web routing for PSR-7 requests. Installation and Autoloading This package is installable and PSR-4 autoloadable via Com

Aura for PHP 469 Jan 1, 2023
: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
Toro is a PHP router for developing RESTful web applications and APIs.

Toro Toro is a PHP router for developing RESTful web applications and APIs. It is designed for minimalists who want to get work done. Quick Links Offi

Kunal Anand 1.2k Dec 27, 2022
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
Thruway - an open source client and router implementation of WAMP (Web Application Messaging Protocol), for PHP.

PHP Client and Router Library for Autobahn and WAMP (Web Application Messaging Protocol) for Real-Time Application Messaging

Voryx 661 Nov 14, 2022
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
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
A PHP Router Package

Router A PHP Router Package Basic Concepts A router package is a utility that, once all http requests are redirected to an entry point, can configure

null 0 Aug 26, 2022
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 router for Amp's HTTP Server.

http-server-router This package provides a routing RequestHandler for Amp's HTTP server based on the request URI and method based on FastRoute. Instal

AMPHP 34 Dec 19, 2022