OSDN Git Service

updated example
[php-libraries/Router.git] / README.md
1 # Simple PHP Router class
2
3 A simple Router class that supports REST routing, named routes and reverse routing. 
4
5 ## Usage
6
7     <?php
8     require 'Router.php';
9
10     $r = new Router();
11
12     // maps / to controller 'users' and method 'index'.
13     $r->match('/','users#index');
14
15     // maps /user/5 to controller 'users', method 'show' with parameter 'id' => 5
16     $r->match('/user/:id','users#show');
17
18     // maps POST request to /users/ to controller 'users' and method 'create'
19     $r->match('/users','users#create',array('via' => 'post'));
20
21
22     // maps GET /users/5/edit to controller 'users', method 'edit' with parameters 'id' => 5 and saves route as a named route.
23     $r->match('/user/:id/edit','users#edit',array('via' => 'get', 'as' => 'user_edit_page'));
24
25     // echoes /users/5/edit
26     echo $r->reverse('user_edit_page',array('id' => '5'));
27
28     // maps multiple routes
29     // GET /users will map to users#index
30     // GET /users/5 will map to users#show
31     $r->resources('users',array('only' => 'index,show'));
32
33
34     if($r->hasRoute()) {
35         // extract controller, action and parameters.
36         extract($r->getRoute());
37
38         ?>
39         <h1>Route found!</h1>
40         <p><b>Controller: </b><?php echo $controller; ?></p>
41         <p><b>Action: </b><?php echo $action; ?></p>
42         <p><b>Params: </b><?php var_dump($params); ?></p>
43         <?php
44
45     } else {
46         ?><h1>No route found.</h1><?php
47     }
48
49 Have a look at example.php or read trough the class' documentation for a better understanding on how to use this class.