OSDN Git Service

Merge pull request #41 from malukenho/master
[php-libraries/Router.git] / README.md
1 # PHP Router class
2
3 A simple Rails inspired PHP router class.
4
5 * Usage of different HTTP Methods
6 * REST / Resourceful routing
7 * Reversed routing using named routes
8 * Dynamic URL's: use URL segments as parameters.
9
10 # Easy to install with **composer**
11
12 ```javascript
13 {
14     "require": {
15         "dannyvankooten/php-router": "dev-master"
16     }
17 }
18 ```
19
20 ## Usage
21
22 ### Friendly URL
23
24 Create a simple .htaccess file on your root directory.
25
26 ```apache
27 Options +FollowSymLinks
28 RewriteEngine On
29 RewriteRule ^(.*)$ index.php [NC,L]
30 ```
31
32 It's a simple example of routers in action
33
34 ```php
35 <?php
36 require __DIR__.'/vendor/autoload.php';
37
38 use PHPRouter\RouteCollection;
39 use PHPRouter\Router;
40 use PHPRouter\Route;
41
42 $collection = new RouteCollection();
43 $collection->attach(new Route('/users/', array(
44     '_controller' => 'someController::users_create',
45     'methods' => 'GET'
46 )));
47
48 $collection->attach(new Route('/', array(
49     '_controller' => 'someController::indexAction',
50     'methods' => 'GET'
51 )));
52
53 $router = new Router($collection);
54 $router->setBasePath('/PHP-Router');
55 $route = $router->matchCurrentRequest();
56
57 var_dump($route);
58 ```
59
60 ## Load routers from a `yaml` file
61
62 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.
63
64 The route definition should follow the example below:
65
66 ```yaml
67 base_path: /blog
68
69 routes:
70   index: [/index, someClass.indexAction, GET]
71   contact: [/contact, someClass.contactAction, GET]
72   about: [/about, someClass.aboutAction, GET]
73 ```
74 In our **Front Controller** would have something like:
75
76 ```php
77 <?php
78 require __DIR__.'/vendor/autoload.php';
79
80 use PHPRouter\RouteCollection;
81 use PHPRouter\Config;
82 use PHPRouter\Router;
83 use PHPRouter\Route;
84
85 $config = Config::loadFromFile(__DIR__.'/router.yaml');
86 $router = Router::parseConfig($config);
87 $router->matchCurrentRequest();
88 ```
89
90 ## More information
91 Have a look at the example.php file or read trough the class' documentation for a better understanding on how to use this class.
92
93 If you like PHP Router you might also like [AltoRouter](//github.com/dannyvankooten/AltoRouter).
94
95 ## License
96 MIT Licensed, http://www.opensource.org/licenses/MIT