1
0
mirror of https://github.com/dannyvankooten/AltoRouter.git synced 2025-08-29 02:49:57 +02:00

19 Commits

Author SHA1 Message Date
Danny van Kooten
0290dc5073 Merge pull request #47 from koenpunt/match-type-fixup
Minor changes for matchTypes
2014-01-08 05:47:24 -08:00
Koen Punt
00a216d1b8 Updated README to include addMatchTypes 2014-01-08 14:41:44 +01:00
Koen Punt
7c53090c1e Use instance methods to set basePath and matchTypes
renamed addMatchType to addMatchTypes
2014-01-08 14:39:18 +01:00
Danny van Kooten
59c41a4990 Merge pull request #45 from osadi/master
Added method for setting new and modifying existing named match types.
2014-01-08 03:39:11 -08:00
Oskar Adin
8a19056553 Added method for setting new and modifying existing named match types.
It's also possible to set these from the constructor.

$router->generate() is now possible with custom regex matches.
2014-01-08 12:28:13 +01:00
Danny van Kooten
d878579e02 Merge pull request #44 from sergey-nagaytsev/patch-1
Create routes and set basePath from constructor call. Thank you Sergey.
2014-01-07 03:14:36 -08:00
sergey-nagaytsev
93e4e4f07e CHG: no Hungarian notation, $arRoute -> $routes 2014-01-07 13:15:53 +03:00
sergey-nagaytsev
62e1d6fa75 ADD: AltoRouter::__construct
Can create in one call from config
2014-01-05 16:08:34 +03:00
Danny van Kooten
8fe62d2883 Updated readme.md to include contributors and a custom regex example 2013-11-11 10:29:28 +01:00
Danny van Kooten
01258d15ef Stripping basePath from route url, only adding it when appropriate. Fixes #38 and #20.
Fixes #38 and #20.
2013-11-08 15:58:39 +01:00
Danny van Kooten
77e77de9fa Changes position of Travis build status 2013-10-09 16:16:50 +02:00
Danny van Kooten
6fd8d8f394 Added travis build status icon to readme 2013-10-09 16:14:56 +02:00
Danny van Kooten
d01067bb28 Merge pull request #36 from koenpunt/php-5
Added PHP 5.5 to Travis config.
2013-10-08 13:43:32 -07:00
Koen Punt
c10205b349 added php 5.5 2013-10-08 10:18:00 +02:00
John Long
78633c2f33 Remove duplicate license statement in composer.json 2013-10-08 00:19:49 -05:00
John Long
2121925965 Merge pull request #33 from Adduc/master
Change autoload from file- to classmap- based for efficiency
2013-10-07 11:47:36 -07:00
Koen Punt
401aa2b311 Merge pull request #35 from koenpunt/fix-tests
fix tests by treating . as part separator (Thank you @joegreen88, closing #26.)
2013-10-07 09:07:51 -07:00
Koen Punt
4d0f9afa24 fix tests by treating . as part separator (Thank you @joegreen88, closing #26) 2013-10-07 18:06:32 +02:00
John Long
9b2a8c179f Change autoload from file- to classmap- based for efficiency 2013-10-07 10:18:57 -05:00
5 changed files with 125 additions and 48 deletions

View File

@@ -2,5 +2,6 @@ language: php
php:
- 5.3
- 5.4
- 5.5
script: phpunit ./
script: phpunit ./

View File

@@ -5,6 +5,30 @@ class AltoRouter {
protected $routes = array();
protected $namedRoutes = array();
protected $basePath = '';
protected $matchTypes = array(
'i' => '[0-9]++',
'a' => '[0-9A-Za-z]++',
'h' => '[0-9A-Fa-f]++',
'*' => '.+?',
'**' => '.++',
'' => '[^/\.]++'
);
/**
* Create router in one call from config.
*
* @param array $routes
* @param string $basePath
* @param array $matchTypes
*/
public function __construct( $routes = array(), $basePath = '', $matchTypes = array() ) {
$this->setBasePath($basePath);
$this->addMatchTypes($matchTypes);
foreach( $routes as $route ) {
call_user_func_array(array($this,'map'),$route);
}
}
/**
* Set the base path.
@@ -14,6 +38,15 @@ class AltoRouter {
$this->basePath = $basePath;
}
/**
* Add named match types. It uses array_merge so keys can be overwritten.
*
* @param array $matchTypes The key is the name and the value is the regex.
*/
public function addMatchTypes($matchTypes) {
$this->matchTypes = array_merge($this->matchTypes, $matchTypes);
}
/**
* Map a route to a target
*
@@ -25,10 +58,6 @@ class AltoRouter {
*/
public function map($method, $route, $target, $name = null) {
if($route != '*') {
$route = $this->basePath . $route;
}
$this->routes[] = array($method, $route, $target, $name);
if($name) {
@@ -61,7 +90,9 @@ class AltoRouter {
// Replace named parameters
$route = $this->namedRoutes[$routeName];
$url = $route;
// prepend base path to route url again
$url = $this->basePath . $route;
if (preg_match_all('`(/|\.|)\[([^:\]]*+)(?::([^:\]]*+))?\](\?|)`', $route, $matches, PREG_SET_ORDER)) {
@@ -101,6 +132,9 @@ class AltoRouter {
$requestUrl = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';
}
// strip base path from request url
$requestUrl = substr($requestUrl, strlen($this->basePath));
// Strip query string (?a=b) from Request Url
if (($strpos = strpos($requestUrl, '?')) !== false) {
$requestUrl = substr($requestUrl, 0, $strpos);
@@ -191,20 +225,12 @@ class AltoRouter {
private function compileRoute($route) {
if (preg_match_all('`(/|\.|)\[([^:\]]*+)(?::([^:\]]*+))?\](\?|)`', $route, $matches, PREG_SET_ORDER)) {
$match_types = array(
'i' => '[0-9]++',
'a' => '[0-9A-Za-z]++',
'h' => '[0-9A-Fa-f]++',
'*' => '.+?',
'**' => '.++',
'' => '[^/]++'
);
$matchTypes = $this->matchTypes;
foreach ($matches as $match) {
list($block, $pre, $type, $param, $optional) = $match;
if (isset($match_types[$type])) {
$type = $match_types[$type];
if (isset($matchTypes[$type])) {
$type = $matchTypes[$type];
}
if ($pre === '.') {
$pre = '\.';

View File

@@ -3,7 +3,7 @@
require 'AltoRouter.php';
class AltoRouterDebug extends AltoRouter{
public function getNamedRoutes(){
return $this->namedRoutes;
}
@@ -15,6 +15,7 @@ class AltoRouterDebug extends AltoRouter{
public function getBasePath(){
return $this->basePath;
}
}
/**
@@ -264,4 +265,29 @@ class AltoRouterTest extends PHPUnit_Framework_TestCase
$this->assertFalse($this->router->match('/some-other-thing', 'GET'));
}
public function testMatchWithCustomNamedRegex()
{
$this->router->addMatchTypes(array('cId' => '[a-zA-Z]{2}[0-9](?:_[0-9]++)?'));
$this->router->map('GET', '/bar/[cId:customId]', 'bar_action', 'bar_route');
$this->assertEquals(array(
'target' => 'bar_action',
'params' => array(
'customId' => 'AB1',
),
'name' => 'bar_route'
), $this->router->match('/bar/AB1', 'GET'));
$this->assertEquals(array(
'target' => 'bar_action',
'params' => array(
'customId' => 'AB1_0123456789',
),
'name' => 'bar_route'
), $this->router->match('/bar/AB1_0123456789', 'GET'));
$this->assertFalse($this->router->match('/some-other-thing', 'GET'));
}
}

View File

@@ -1,64 +1,89 @@
# AltoRouter
# AltoRouter [![Build Status](https://api.travis-ci.org/dannyvankooten/AltoRouter.png)](http://travis-ci.org/dannyvankooten/AltoRouter)
AltoRouter is a small but powerful routing class for PHP 5.3+, heavily inspired by [klein.php](https://github.com/chriso/klein.php/).
* Dynamic routing with named parameters
* Reversed routing
* Flexible regular expression routing (inspired by [Sinatra](http://www.sinatrarb.com/))
* Custom regexes
## Getting started
1. PHP 5.3.x is required
2. Install AltoRouter using Composer or manually
2. Setup URL rewriting so that all requests are handled by **index.php**
3. Create an instance of AltoRouter, map your routes and match a request.
4. Have a look at the supplied example file for a better understanding on how to use AltoRouter(index.php).
4. Have a look at the example `index.php` file for a better understanding on how to use AltoRouter(index.php).
## Routing
```php
$router = new AltoRouter();
$router->setBasePath('/AltoRouter');
$router->setBasePath('/AltoRouter'); // (optional) the subdir AltoRouter lives in
// mapping routes
$router->map('GET|POST','/', 'home#index', 'home');
$router->map('GET','/users/', array('c' => 'UserController', 'a' => 'ListAction'));
$router->map('GET','/users', array('c' => 'UserController', 'a' => 'ListAction'));
$router->map('GET','/users/[i:id]', 'users#show', 'users_show');
$router->map('POST','/users/[i:id]/[delete|update:action]', 'usersController#doAction', 'users_do');
// reversed routing
$router->generate('users_show', array('id' => 5));
```
You can use the following limits on your named parameters. AltoRouter will create the correct regexes.
**You can use the following limits on your named parameters. AltoRouter will create the correct regexes for you.**
```php
* // Match all request URIs
[i] // Match an integer
[i:id] // Match an integer as 'id'
[a:action] // Match alphanumeric characters as 'action'
[h:key] // Match hexadecimal characters as 'key'
[:action] // Match anything up to the next / or end of the URI as 'action'
[create|edit:action] // Match either 'create' or 'edit' as 'action'
[*] // Catch all (lazy, stops at the next trailing slash)
[*:trailing] // Catch all as 'trailing' (lazy)
[**:trailing] // Catch all (possessive - will match the rest of the URI)
.[:format]? // Match an optional parameter 'format' - a / or . before the block is also optional
Some more complicated examples
/posts/[*:title][i:id] // Matches "/posts/this-is-a-title-123"
/output.[xml|json:format]? // Matches "/output", "output.xml", "output.json"
/[:controller]?/[:action]? // Matches the typical /controller/action format
* // Match all request URIs
[i] // Match an integer
[i:id] // Match an integer as 'id'
[a:action] // Match alphanumeric characters as 'action'
[h:key] // Match hexadecimal characters as 'key'
[:action] // Match anything up to the next / or end of the URI as 'action'
[create|edit:action] // Match either 'create' or 'edit' as 'action'
[*] // Catch all (lazy, stops at the next trailing slash)
[*:trailing] // Catch all as 'trailing' (lazy)
[**:trailing] // Catch all (possessive - will match the rest of the URI)
.[:format]? // Match an optional parameter 'format' - a / or . before the block is also optional
```
## Additional info
If you like AltoRouter, you might also like [PHP Router](//github.com/dannyvankooten/PHP-Router).
**Some more complicated examples**
```php
@/(?[A-Za-z]{2}_[A-Za-z]{2})$ // custom regex, matches language codes like "en_us" etc.
/posts/[*:title][i:id] // Matches "/posts/this-is-a-title-123"
/output.[xml|json:format]? // Matches "/output", "output.xml", "output.json"
/[:controller]?/[:action]? // Matches the typical /controller/action format
```
**The character before the colon (the 'match type') is a shortcut for one of the following regular expressions**
```php
'i' => '[0-9]++'
'a' => '[0-9A-Za-z]++'
'h' => '[0-9A-Fa-f]++'
'*' => '.+?'
'**' => '.++'
'' => '[^/\.]++'
```
**New match types can be added using the `addMatchTypes()` method**
```php
$router->addMatchTypes(array('cId' => '[a-zA-Z]{2}[0-9](?:_[0-9]++)?'));
```
## Contributors
- [Danny van Kooten](https://github.com/dannyvankooten)
- [Koen Punt](https://github.com/koenpunt)
- [John Long](https://github.com/adduc)
- [Niahoo Osef](https://github.com/niahoo)
## License
(MIT License)
Copyright (c) 2012-2013 Danny van Kooten <dannyvankooten@gmail.com>
Copyright (c) 2012-2013 Danny van Kooten <hi@dannyvankooten.com>
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:

View File

@@ -23,7 +23,6 @@
"php": ">=5.3.0"
},
"autoload": {
"files": ["AltoRouter.php"]
},
"license" : "MIT"
"classmap": ["AltoRouter.php"]
}
}