webcretaire/diggy-router

Simple routing component for PHP

v1.5.0 2018-07-05 22:15 UTC

This package is auto-updated.

Last update: 2024-03-29 03:38:16 UTC


README

Latest Stable Version Total Downloads License Build Status

Simple routing component for php

Installation

Currently the only way of installing is via composer :

composer require webcretaire/diggy-router

Basic Usage

First you have to register the routes you want to use in a YAML file with the following structure :

routes:
  # First Route
  - uri: '/addressOfYourPage'
    controller: 'Name\Of\A\Class'
    action: 'nameOfTheFunctionToCall'
  # Second Route
  - uri: '/addressOfYourSecondPage'
    controller: 'Name\Of\A\Class'
    action: 'nameOfTheFunctionToCall'
  # ...

Note that the "action" parameter is optionnal, if it is not provided the router will try to call a "render()" function with no parameters

Then create a new router :

$router = new DiggyRouter\Router()

Load your routes into the router :

$router->loadRoutes("path/to/your/routing.yml");

Use the router to call the correct function in the correct controller according to the requested URI :

$router->handleRequest();

Advanced usage

By default the router tries to find a route that matches the requested URI which is stored in $_SERVER['REQUEST_URI'], but you can specify the URI to use by passing it to the function :

$router->handleRequest($customURI);

DiggyRouter now supports multiple URIs for one route, you just have define the uri parameter of your route as an array :

routes:
  - uri: 
      - '/firstPage'
      - '/secondPage'
    controller: 'Name\Of\A\Class'
    action: 'nameOfTheFunctionToCall'
  # ...

If you have complex URIs, you can specify an expression that the requested URI must match. The default delimiter is '~' but you can specify which one to use by doing :

$router->setDelimiter('YourDelimiter');

If you have a lot of URIs, you can split your routes between one main routing file and as many secondary files as you want :

# Main routing file
includes:
  - 'secondRoutingFile'
  - 'thirdRoutingFile'

routes:
  - uri: '/SomeAdditionnalRoutes'
    controller: 'Name\Of\A\Class'
  # ...
# Second routing file
routes:
  - uri: '/RoutesEverywhere'
    controller: 'Name\Of\A\Class'
  # ...

Examples

You can see a full example in this routing file