Skip to content

pifaace/please-route-me

Repository files navigation

Please-route-me

Build Status Scrutinizer Code Quality Code Intelligence Status

Getting started

Please-route-me is a router built around one main object called Router. It allows you to define a route, match an requested route, get all routes and more. In other words, to getting started you have to instantiate this Router object :

<?php
   use Piface\Router\Router;

   $router = new Router();

Then you can start to add a custom route.

Adding a simple route

To add a route, GET for the example, declare it like this :

<?php
    $router->get('/home', 'home', function () {
       echo 'hi from home';
    });

Each route you will create will be built with the same three parameters.

  • a $path
  • A $name
  • A callback or a string like name's controller
<?php
    $router->get('/home', 'home', 'indexController@home');

obviously, you need to implement a controller resolver to do that.

In a second time, you can easily add some parameters in your route definition :

<?php
    $router->get('/user/{id}', 'user', function ($id) {
       echo 'welcome user ' . $id;
    });

Matching a route from the Request

To match a PSR-7 ServerRequestInterface, you can call the matcher() from Router

<?php
    $route = $router->match($request);

The method will return a Route object or null if no available route is found.

Here some packages that you can implement.

Full example

This example below comes from an index.php that implements the router :

<?php

use Piface\Router\Router;

require dirname(__DIR__) . '/vendor/autoload.php';

$router = new Router();

$router->get('/home/{id}/{foo}', 'home', function ($id) {
   echo 'hi from home ' . $id;
})->where(['id' => '[0-9]+']);

$request = \GuzzleHttp\Psr7\ServerRequest::fromGlobals();

$route = $router->match($request);

// call the action route
\call_user_func_array($route->getAction(), $route->getParameters()); // hi from home $id

Contributing

If you want to try in development environnement :

$ composer install
$ php -S localhost:8080 -d display_error=1 -t examples/
$ open http://localhost:8080/home/13/bar

Go further

These topics cover the advanced usages of the router :

Releases

No releases published

Packages

No packages published

Languages