mattvb91/lightrouter

Lightweight Router

0.1.0 2017-06-28 16:26 UTC

This package is auto-updated.

Last update: 2024-05-14 20:24:59 UTC


README

LightRouter

68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f6d617474766239312f4c69676874526f757465722f62616467652e7376673f6272616e63683d6d6173746572 68747470733a2f2f7472617669732d63692e6f72672f6d617474766239312f4c69676874526f757465722e7376673f6272616e63683d6d6173746572 68747470733a2f2f706f7365722e707567782e6f72672f6d617474766239312f6c69676874726f757465722f762f737461626c65 68747470733a2f2f706f7365722e707567782e6f72672f6d617474766239312f6c69676874726f757465722f646f776e6c6f616473 68747470733a2f2f706f7365722e707567782e6f72672f6d617474766239312f6c69676874726f757465722f762f756e737461626c65 68747470733a2f2f706f7365722e707567782e6f72672f6d617474766239312f6c69676874726f757465722f6c6963656e7365

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

$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.

$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:

$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:

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:

//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:

public class CustomModel implements LightRouteModelInterface
{
    public static function getForLightRoute($routeParam): LightRouteModelInterface
    {
        //Use $routeParam to load your model class and return the instance
    }
}