2018-03-12 10:49:55 -05:00
|
|
|
# Simple PHP Router
|
|
|
|
|
2018-03-13 10:01:52 -05:00
|
|
|
Hey! This is a simple and small php router that can handel the whole url routing for your project.
|
2018-03-12 10:49:55 -05:00
|
|
|
It utilizes RegExp and PHPs anonymous functions to create a lightweight and fast routing system.
|
2018-03-13 10:01:52 -05:00
|
|
|
The router supports dynamic path parameters, special 404 and 405 routes as well as verification of request methods like get, post, put, delete etc...
|
|
|
|
The codebase is very small and very easy to understand. So you can use it as boilerplate for a more complex router.
|
2018-03-12 10:49:55 -05:00
|
|
|
|
2018-03-13 10:05:11 -05:00
|
|
|
Take a look at the index.php file. As you can see the ```Route::add()``` method is used to add new routes to your project.
|
|
|
|
The first argument takes the path segment. You can also use RegExp in there to parse out variables.
|
2018-03-13 10:01:52 -05:00
|
|
|
All matching variables will be pushed to the handler method.
|
2018-03-13 10:05:11 -05:00
|
|
|
The second argument will match the request method. The default method is 'get'.
|
2018-03-12 10:49:55 -05:00
|
|
|
|
2018-03-13 10:01:52 -05:00
|
|
|
## Simple example:
|
2018-03-12 10:49:55 -05:00
|
|
|
```
|
2018-03-13 10:01:52 -05:00
|
|
|
include('Route.php');
|
|
|
|
|
|
|
|
Route::add('/user/([0-9]*)/edit',function($id){
|
2018-03-13 10:27:14 -05:00
|
|
|
echo 'Edit user with id '.$id.'<br/>';
|
2018-03-13 10:01:52 -05:00
|
|
|
},'get');
|
|
|
|
|
|
|
|
Route::run('/');
|
2018-03-12 10:49:55 -05:00
|
|
|
```
|
|
|
|
|
2018-03-13 10:01:52 -05:00
|
|
|
You will find a more complex example with a build in navigation in the index.php file.
|
|
|
|
|
|
|
|
## Use a different basepath
|
|
|
|
If your script lives in a subfolder e.g. /api/v1 set this basepath in your run method:
|
2018-03-13 10:05:11 -05:00
|
|
|
|
2018-03-13 10:01:52 -05:00
|
|
|
```Route::run('/api/v1');```
|
2018-03-13 10:05:11 -05:00
|
|
|
|
|
|
|
Do not forget to edit the basepath in .htaccess if you are on apache.
|
2018-03-12 11:12:05 -05:00
|
|
|
|
|
|
|
## Something does not work?
|
2018-03-13 10:01:52 -05:00
|
|
|
* Dont forget to set the correct basepath as argument in your run method and in your .htaccess file.
|
2018-03-12 11:12:05 -05:00
|
|
|
* Enable mod_rewrite in your apache settings
|