library router
Router for PHP. Simple, lightweight and convenient.
delight-im/router
Router for PHP. Simple, lightweight and convenient.
- Wednesday, January 24, 2018
- by delight-im
- Repository
- 3 Watchers
- 17 Stars
- 325 Installations
- PHP
- 3 Dependents
- 0 Suggesters
- 3 Forks
- 0 Open issues
- 5 Versions
- 18 % Grown
PHP-Router
Router for PHP. Simple, lightweight and convenient., (*1)
Requirements
Installation
-
Include the library via Composer [?]:, (*2)
$ composer require delight-im/router
-
Include the Composer autoloader:, (*3)
require __DIR__ . '/vendor/autoload.php';
Usage
-
Enable URL rewriting on your web server, (*4)
-
Apache (in .htaccess
or httpd.conf
), (*5)
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . index.php [L]
-
Nginx (in nginx.conf
), (*6)
try_files $uri /index.php;
-
Create a new Router
instance, (*7)
-
for the web root, (*8)
$router = new \Delight\Router\Router();
-
for any subdirectory, (*9)
$router = new \Delight\Router\Router('/my/base/path');
-
Add some routes and map them to anonymous functions or closures, (*10)
-
Static route:, (*11)
$router->get('/', function () {
// do something
});
-
Dynamic route (with parameters):, (*12)
$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., (*13)
-
Route with multiple supported request methods:, (*14)
$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, (*15)
// 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), (*16)
class MyController {
public static function someStaticMethod($database, $uuid) {
// do something
}
}
and, (*17)
$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., (*18)
License
This project is licensed under the terms of the MIT License., (*19)