https://github.com/mattvb91/lightrouter
Lightweight PHP Router
https://github.com/mattvb91/lightrouter
php php-library php-router php7
Last synced: 7 months ago
JSON representation
Lightweight PHP Router
- Host: GitHub
- URL: https://github.com/mattvb91/lightrouter
- Owner: mattvb91
- License: mit
- Created: 2017-06-24T14:30:50.000Z (almost 9 years ago)
- Default Branch: master
- Last Pushed: 2017-06-28T16:26:26.000Z (almost 9 years ago)
- Last Synced: 2025-01-01T23:15:29.069Z (over 1 year ago)
- Topics: php, php-library, php-router, php7
- Language: PHP
- Size: 16.6 KB
- Stars: 2
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE.md
Awesome Lists containing this project
README
LightRouter
## LightRouter
Lightweight PHP router class. This is a test project. If you need a reliable & fully
tested solution please check out FastRoute or AltoRouter.
### Basic Usage
```php
$router = new mattvb91\LightRouter\Router();
$router->addRoute('/', MyController::class);
$router->run();
```
### Defining Routes
To add new routes use the ```$router->addRoute()``` method. If no action is defined
it will default to ```index``` which will be needed on your controller.
You will need to pass the route path & either a controller or a closure. If you do
not specify an action it will default to 'index' which will be required on
your controller.
```php
$router->addRoute('/', MyController::class);
$router->addRoute('/contact', MyController::class, 'contact');
$route->addRoute('/hello', function() {
echo 'Hello world';
});
```
### Defining parameters
Passing parameters into your controller actions can be done using a `:parameter` attribute
in your route definition:
```php
$router->addRoute('/view/:param', MyController::class);
```
Your method parameter must match the defined route parameter. In our example above
our controllers ```view``` method would look like this:
```php
public function view($param)
{
}
```
### Automatically Injecting Models
If you are using the ```LightModel``` ORM package for your DB models you can automatically
inject the associated model by specifying the instance type in your
controller action:
```php
//Your route definition
$router->addRoute('/user/view/:user', UserController::class, 'view');
//In your UserController::class
public function view(User $user)
{
//$user is already fully loaded for you.
}
```
If you are using your own ORM or other DB model class you can also implement
the ```LightRouteModelInterface::class``` in your custom model which expects
you to return the fully loaded instance.
LightRouter will pass the associated $key from your route into the ```getForLightRoute``` method:
```php
public class CustomModel implements LightRouteModelInterface
{
public static function getForLightRoute($routeParam): LightRouteModelInterface
{
//Use $routeParam to load your model class and return the instance
}
}
```