delight-im / router
Router for PHP. Simple, lightweight and convenient.
Installs: 1 963
Dependents: 1
Suggesters: 0
Security: 0
Stars: 38
Watchers: 4
Forks: 6
Open Issues: 4
Requires
- php: >=5.6.0
README
Router for PHP. Simple, lightweight and convenient.
Requirements
- PHP 5.6.0+
Installation
-
Include the library via Composer [?]:
$ composer require delight-im/router
-
Include the Composer autoloader:
require __DIR__ . '/vendor/autoload.php';
Usage
-
Enable URL rewriting on your web server
-
Apache (in
.htaccess
orhttpd.conf
)RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule . index.php [L]
-
Nginx (in
nginx.conf
)try_files $uri /index.php;
-
-
Create a new
Router
instance-
for the web root
$router = new \Delight\Router\Router();
-
for any subdirectory
$router = new \Delight\Router\Router('/my/base/path');
-
-
Add some routes and map them to anonymous functions or closures
-
Static route:
$router->get('/', function () { // do something });
-
Dynamic route (with parameters):
$router->get('/users/:id/photo', function ($id) { // get the photo for user `$id` });
The values of parameters matched in the URL can be captured as arguments in the callback.
-
Route with multiple supported request methods:
$router->any([ 'POST', 'PUT' ], '/users/:id/address', function ($id) { // update the address for user `$id` });
-
-
Map routes to controller methods instead for more complex callbacks
// use static methods $router->get('/photos/:id/convert/:mode', [ 'PhotoController', 'myStaticMethod' ]); // or // instance methods $router->get('/photos/:id/convert/:mode', [ $myPhotoController, 'myInstanceMethod' ]);
-
Inject arguments for access to further values and objects (prepended to those matched in the route)
class MyController { public static function someStaticMethod($database, $uuid) { // do something } }
and
$database = new MyDatabase(); // ... $router->delete('/messages/:uuid', [ 'MyController', 'someStaticMethod' ], [ $database ]);
Contributing
All contributions are welcome! If you wish to contribute, please create an issue first so that your feature, problem or question can be discussed.
License
This project is licensed under the terms of the MIT License.