A web router implementation for PHP.

Overview

Aura.Router

Powerful, flexible web routing for PSR-7 requests.

Installation and Autoloading

This package is installable and PSR-4 autoloadable via Composer as aura/router.

Alternatively, download a release, or clone this repository, then map the Aura\Router\ namespace to the package src/ directory.

Dependencies

This package requires PHP 5.5 or later; it has been tested on PHP 5.6, PHP 7, PHP 7.1 and HHVM. We recommend using the latest available version of PHP as a matter of principle.

Aura library packages may sometimes depend on external interfaces, but never on external implementations. This allows compliance with community standards without compromising flexibility. For specifics, please examine the package composer.json file.

Quality

Scrutinizer Code Quality Code Coverage Build Status

To run the unit tests at the command line, issue composer install and then ./vendor/bin/phpunit at the package root. (This requires Composer to be available as composer.)

This package attempts to comply with PSR-1, PSR-2, and PSR-4. If you notice compliance oversights, please send a patch via pull request.

Community

To ask questions, provide feedback, or otherwise communicate with other Aura users, please join our Google Group, follow @auraphp, or chat with us on Freenode in the #auraphp channel.

Documentation

This package is fully documented here.

There is also a video demonstration on YouTube:

Version 3 video tutorial on Aura.Router

Comments
  • front controller in subdirectory

    front controller in subdirectory

    I know this sounds silly....but I cannot make the router to recognize urls when the index.php is inside a subdirectory. I added the RewriteBase rule but still the router works only if I prepend the subdirectory in rooute definitions.

    /path/to/project/web/subdir/index.php
    // web/ is the public web folder, the docroot
    
    $dispatcher->setObject('hello',//doesn't work
    $dispatcher->setObject('subdir/hello',// works...
    

    what am i missing?

    opened by pine3ree 20
  • BC break: remove 'controller' from route modification

    BC break: remove 'controller' from route modification

    This break makes Action-Domain-Responder the primary idiom, instead of Model-View-Controller. Previously, the $route_callable would set both 'controller' and 'action' params in the route; now, it sets only 'action', and it is just a copy of the route name.

    You can regain the old MVC route modifications with this:

    <?php
        $router->setRouteCallable(function ($route) {
            $action = $route->name;
            if (! $action) {
                return;
            }
    
            $controller = null;
            $pos = strrpos($action, '.');
            if ($pos !== false) {
                $controller = substr($action, 0, $pos);
                $action = substr($action, $pos + 1);
            }
    
            if (! isset($route->values['controller'])) {
                $route->addValues(array('controller' => $controller));
            }
    
            if (! isset($route->values['action'])) {
                $route->addValues(array('action' => $action));
            }
        });
    ?>
    
    opened by pmjones 19
  • Using the Generator as a View Helper

    Using the Generator as a View Helper

    I want to use the Generator in a view script. It seems like I want to be able to do it like this, I guess?

    // view.php
    echo $this->a(
        $this->url()->generate('route', $params),
        'click here'
    );
    // or possibly even:
    echo $this->a(
        $this->url('route', $params),
        'click here'
    );
    

    I did it like this the other day, and it seemed a little awkward. I set up my DI to grab the Aura\Html helper locator, and set the url key to a lazyGetCall on the router, and then wrapped that in a function...

    <?php
    class Config extends ContainerConfig
    {
        public function modify(Container $di)
        {
            $helpers = $di->get('aura/html:helpers');
            $url = $di->lazyGetCall('radar/adr:router', 'getGenerator');
            $helpers->set(
                'url',
                function () use ($url) {
                    return $url;
                }
            );
        }
    }
    

    ...That seems pretty weird though.

    If Generator had this:

    //...
    public function __invoke($name = null, $data = [])
    {
        if (null == $name) {
            return $this;
        }
    
        return $this->generate($name, $data);
    }
    

    I wouldn't need to wrap it in a function to use with the helpers, and I could just call $this->url(...), instead of $this->url()->generate(...), but if needed, could also $this->url()->generateRaw(...)

    However, again... it doesnt seem quite right to me to add the __invoke method like that in the Generator.

    Maybe I should just be adding it into the view and not mess with the helpers? eg:

    <?php
    class Config extends ContainerConfig
    {
        public function modify(Container $di)
        {
            $view = $di->get('aura/view:view');
            $generator = $di->get('radar/adr:router')->getGenerator();
            $view->addData(['urlHelper' => $generator]);
        }
    }
    
    // in view:
    echo $this->a(
        $this->urlHelper->generate('route', $params),
        'click here'
    );
    

    Are other people doing this? Thoughts? Recommendations? Best Practices?

    opened by jakejohns 16
  • Generic Generator view helper

    Generic Generator view helper

    Quick helper using the Generator as an injectable and utilizing one of @jakejohns ideas about returning the generator or it's results when __invoke is used.

    opened by dlundgren 14
  • Format seems not recognizing

    Format seems not recognizing

    The whole code I have is

    <?php
    $package_dir = dirname( __DIR__ ) . '/auraphp/system/package';
    $loader = require_once $package_dir . '/Aura.Autoload/scripts/instance.php';
    $loader->add('Aura\Router\\', $package_dir . '/Aura.Router/src/' );
    $loader->register();
    use Aura\Router\Map;
    use Aura\Router\RouteFactory;
    $map = new Map(new RouteFactory);
    
    $map->add('home', '/');
    
    $map->add(null, '/{:controller}/{:action}/{:id}');
    
    $map->add('read', '/blog/read/{:id}{:format}', [
        'params' => [
            'id' => '(\d+)',
            'format' => '(\.json|\.html)?',
        ],
        'values' => [
            'controller' => 'blog',
            'action' => 'read',
            'format' => '.html',
        ]
    ]);
    
    $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
    
    //echo $path . '<pre>' . print_r( $map->getRoutes() , true );
    
    $route = $map->match($path, $_SERVER);
    if (! $route) {
        // no route object was returned
        echo "No application route was found for that URI path.";
        exit;
    }
    echo " Controller : " . $route->values['controller'];
    echo " Action : " . $route->values['action'];
    echo " Format : " . $route->values['format'];
    

    Started server via php -S localhost:8000

    http://localhost:8000/blog/read/1

    Controller : blog Action : read Notice: Undefined index: format in /media/Linux/auracomponentstest/index.php on line 38 Format : Yes the format is not there , so the error , but

    http://localhost:8000/blog/read/1.html

    http://localhost:8000/blog/read/1.json

    all throwing

    `Not Found

    The requested resource /blog/read/1.html was not found on this server.`

    opened by harikt 14
  • setIsMatchCallable for version 3.x

    setIsMatchCallable for version 3.x

    Hello,

    I recently upgraded my project from version 2.x to 3.x of aura router. In the previous version I used the method: ->setIsMatchCallable(function(array $server, \ArrayObject $matches)

    but It seems it dissapeared (or it is hidden within other method). Could you point me where it is?

    In case the feature is not available for 3.x, could it be possible to be updated with it?

    Thanks !

    Featured-request version2 
    opened by Ricael 13
  • Configuring the router with an array

    Configuring the router with an array

    Hi there!

    I've been using Aura's router a tiny bit (still at noob level to be honest) and the first thing I did was write something that allows me to configure the routes using an array. Example (from here):

    $routes = [
        'home'    => [
            'pattern'    => '/',
            'controller' => HomeController::class,
        ],
        'project' => [
            'pattern'    => '/project/{user}/{repository}',
            'controller' => ProjectController::class,
        ],
    ];
    
    // Then later on:
    $router = (new RouterFactory())->newInstance();
    foreach ($routes as $routeName => $route) {
        $router->add($routeName, $route['pattern'])
            ->addValues(['controller' => $route['controller']]);
    }
    

    This is of course very basic, but I was wondering if you have ever considered and discussed something like that. I guess that wouldn't fit everybody's usage, but for my usage, that's the only way I would use a router as soon as I get more than 2 routes.

    opened by mnapoli 12
  • Without url encode in generate

    Without url encode in generate

    Is it possible to create urls without urlencode ?

    Eg : in aura/asset-bundle when we pass the file path as /css/something.css all will be converted to %2Fcss%2Fsomething.css . That means even when we have the real path with some sort of file moved, the css may not get loaded.

    Any idea to fix for routes like that ?

    opened by harikt 12
  • Implemented bracketed optional parameters

    Implemented bracketed optional parameters

    This allows one to create routes like

    • [/{language}]/pages[.{type}] which will match /pages and /en/pages and /en/pages.json
    • posts/archive[/{year}][/{month}][/{day}]

    The generate() method makes sure that parameters that have the default value are not included. So, if the language default value is en the URL that will be generated will NOT start with /en

    opened by adrianmiu 10
  • Latest update to the 1.x branch breaks 5.3 compatibility with shorthand arrays.

    Latest update to the 1.x branch breaks 5.3 compatibility with shorthand arrays.

    The latest update in this commit: https://github.com/auraphp/Aura.Router/commit/0bcdaa1168b338a97ae3c7da8d5c607e13695236 breaks php 5.3 compatibility. Was this intentional or an oversight as the blogpost announcing the update states "you should be able to update-in-place without any problems" which wont be the case for anyone on 5.3.

    I know 5.4 or above is desirable, but is it really worth killing off 5.3 over a handful of shorthand arrays? There's surely no need for that is there?

    opened by rickmills 9
  • Document example codes not working.

    Document example codes not working.

    PHP message: PHP Fatal error: Uncaught Error: Call to a member function getBody() on null And it turns out that this had been fixed before Please fix it so someone who wishes to try aura.router will be able to use it.

    opened by cwhsu1984 8
  • More explanation

    More explanation

    use Aura\Router\RouterContainer;
    /**
    	 * Database Connector
    	 * 
    	 * @link https://www.watermelon.lucychats.com/docs for Programming Tutorials
    	 * @author lucychats <[email protected]>
    	 */
        include __DIR__ . '/autoload.php';
    
        $routerContainer = new RouterContainer();
        $map = $routerContainer->getMap();
    
        $map->get('blog.read', '/index/{id}', function ($request) {
            $id = (int) $request->getAttribute('id');
            $response = new \Zend\Diactoros\Response();
            $response->getBody()->write("You asked for blog entry {$id}.");
            echo $response;
        });
    

    I have the code on my index.php page with .htaccess

    RewriteEngine on
    
    Options All -Indexes
    
    RewriteRule ^$ index.php [QSA]
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php/$1 [QSA,L]
    
    RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
    RewriteRule ^ %1 [R=301,L]
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteRule ^(.*?)/?$ $1.php [NC,L]
    
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME}\.html -f
    RewriteRule ^(.*)$ $1.html [NC,L]
    
    

    I tried outputing the id arugument of the route but nothing is showing...

    Am a newbie in working with route please give me more explanations on how to do this... Thanks.

    Question 
    opened by mitmelon 1
  • Basepath concatenation could be improved

    Basepath concatenation could be improved

    Currently, basepath is simply concatenated with the path regex used in a route.

    This can lead to confusing results when, say, basepath is websites/ and the route is /testpage, since Aura.Router currently will concatenate this to websites//testpage.

    I have implemented a fix for this on my fork as follows:

    // Trim leading and following slashes from basepath
    $basePart = trim($this->basepath, '/');
    
    // Trim leading slash from route path
    $routePart = ltrim($this->route->path, '/');
    
    // Join basepath and route with forwardslash
    $this->regex = '/' . implode('/', array($basePart, $routePart));
    

    This works great, but I found out it's too lenient. When I ran phpunit I noticed it breaks 12 test cases :/

    I'll try to figure out a fix that doesn't cause this issues, but in the meantime I'll post this issue in case I forget.

    opened by KernelDeimos 3
  • Unable to generate URL with port number

    Unable to generate URL with port number

    I'm running an application at http://127.0.0.1:1244/ and I want to generate an absolute URI using the \Aura\Router\Generator. As I understand it I need to specify a ->host() for the route in order to get an absolute URI. But there is no way to set a port number. I can set the port number together with the host name ->host('127.0.0.1:1244') but then the \Aura\Router\Matcher won't match anymore.

    Any ideas how to get around this problem?

    PS: I'm using Aura.Router 3.1.0

    opened by smichaelsen 2
Releases(3.2.0)
  • 3.2.0(Feb 1, 2022)

    1. Various documentation and doc block improvements by @muglug, @johnnypeck, Andreas Sundqvist, @afilina, @vitorbari, @bkdotcom, @daniel-mueller, @cxj, @koriym
    2. CI improvements @jakejohns, @koriym,
    3. 8.1 support @koriym, @fisharebest
    4. Fixes #178 psr/log version 3 support @koriym
    5. Fixed #162 by @NaokiTsuchiya and @harikt
    6. Fixed #169 by @harikt
    Source code(tar.gz)
    Source code(zip)
  • 3.1.0(Mar 2, 2017)

    This release adds three new features:

    • Route URL view helpers
    • Support for custom token matching logic
    • Support for route-specific matching logic

    Documentation, examples, and tests have also been updated.

    Source code(tar.gz)
    Source code(zip)
  • 3.0.1(Oct 3, 2016)

  • 2.3.1(Oct 3, 2016)

  • 3.0.0(Dec 1, 2015)

  • 2.3.0(Jul 17, 2015)

    This release adds support for a "base path" to routes. See #84, #86, and #96 for background and information. Thanks to @pine3ree and @harikt for their foundational work on this feature!

    Source code(tar.gz)
    Source code(zip)
  • 3.0.0-beta2(Jul 16, 2015)

  • 3.0.0-beta1(Jun 15, 2015)

  • 3.0.0-alpha2(May 24, 2015)

  • 3.0.0-alpha1(May 18, 2015)

  • 2.2.2(Mar 27, 2015)

  • 2.2.1(Mar 15, 2015)

  • 2.2.0(Nov 10, 2014)

  • 2.1.2(Nov 7, 2014)

  • 2.1.1(Oct 22, 2014)

  • 2.1.0(Oct 5, 2014)

  • 2.0.0(Aug 29, 2014)

    First stable 2.0 release.

    • DOC: Update README and docblocks.
    • ADD: Methods Route::setAccept() and Route::addAccept() to match against "Accept" headers.
    • ADD: Methods Route::setMethod() and Route::addMethod() to explicitly match against HTTP methods.
    • ADD: Testing on Travis for PHP 5.6.
    • ADD: Method Router::addHead() to add a HEAD route
    • ADD: Methods Router::getFailedRoute(), Route::failedMethod(), and Route::failedAccept(), along with route match scoring, to inspect the closest non-matching route.
    • REF: Various refactorings to extract complex code to separate classes
    • BRK: The routes no longer add a "controller" value by default; instead, they add only an "action" value that defaults to the route name. This makes the package ADR-centric by default instead of MVC-centric.
    • CHG: Use ArrayObject for value matches
    • CHG: Method Router::attachResource() now adds an "OPTIONS" route.
    • REF: Extract a Generator class from the Route class
    • ADD: Generator::generateRaw() to use raw values in the route; you will need to encode them yourself.
    • ADD: Method Router::getMatchedRoute() for use after matching.
    • ADD: Class-based config for Aura.*_Kernel packages.
    Source code(tar.gz)
    Source code(zip)
  • 2.0.0-beta1(Jan 8, 2014)

Owner
Aura for PHP
High-quality, well-tested, standards-compliant, decoupled libraries that can be used in any codebase.
Aura for PHP
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
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
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
: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
:bird: 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
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
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 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 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
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
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
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