https://github.com/ext/php-routes
Routing for MVC-ish PHP projects.
https://github.com/ext/php-routes
Last synced: about 1 year ago
JSON representation
Routing for MVC-ish PHP projects.
- Host: GitHub
- URL: https://github.com/ext/php-routes
- Owner: ext
- License: bsd-3-clause
- Created: 2014-09-01T22:36:47.000Z (almost 12 years ago)
- Default Branch: master
- Last Pushed: 2025-04-07T14:32:55.000Z (about 1 year ago)
- Last Synced: 2025-04-12T20:52:09.341Z (about 1 year ago)
- Language: PHP
- Homepage: http://php-routes.readthedocs.io/en/latest/
- Size: 236 KB
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- Contributing: CONTRIBUTING.md
- License: COPYING
Awesome Lists containing this project
README
PHP-routes
==========
[](https://github.com/ext/php-routes/actions/workflows/php.yml) [](https://coveralls.io/github/ext/php-routes?branch=master)
[](http://php-routes.readthedocs.io/en/latest/)
Routing for MVC-ish PHP projects.
composer require sidvind/php-routes
Example
-------
Put routes in a separate file, e.g. `routes.php`:
```php
'MyController#foo']);
$post('bar/:id/baz', ['to' => 'MyController#update']); /* use :var for variables */
/* automatically setup RESTful routes */
$resource('article', [], function($r){
$r->members(function($r){
$r->patch('frobnicate'); /* maps to PATCH /article/:id/frobnicate */
});
$r->collection(function($r){
$r->patch('twiddle'); /* maps to PATCH /article/twiddle */
});
});
/* scoping */
$scope(':lang', [], function($r){
$r->get('barney'); /* maps to GET /:lang/barney */
});
```
Create a dispatcher:
```php
match($url, $method) ){
$class = "{$match->controller}Controller";
$controller = new $class();
return call_user_func_array([$controller, $match->action], $match->args);
} else {
/* 404 */
}
}
}
$router = new Dispatcher('routes.php');
$router->dispatch($url, $method);
```
To preview/debug routes use `bin/php-routes`:
```
# bin/php-routes routes.php
GET /foo MyController#foo #^/foo(?P\.\w+)?$#
POST /bar/:id/baz MyController#update #^/bar/(?P[A-Za-z0-9\-_\.]+)/baz(?P\.\w+)?$#
article GET /article Article#list #^/article(?P\.\w+)?$#
...
# bin/php-routes routes.php get /foo
Controller: MyController
Action: foo
Format:
Arguments:
[]
# bin/php-routes routes.php get /bar
bin/php-routes: url doesn't match any route.
```