Skip to content

php-strict/simple-route

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

54 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Simple route

Software License Build Status codecov Codacy Badge

Simple request router. All routes is a key/entry pairs. Router looking for entry closest to key, and returns it with remainder of searching key as parameters array (splited by slash).

It can be used to delegate execution from core to standalone modules. Each module takes remainder of searching key as parameters array and use it by its own.

Storage example:

<?php
return [
    '/'         => ['some callback, module class, ... here'],
    '/qwe'      => ['some callback, module class, ... here'],
    '/asd'      => ['some callback, module class, ... here'],
    '/qwe/rty'  => ['some callback, module class, ... here'],
    '/asd/fgh'  => ['some callback, module class, ... here'],
];

For path '/qwe/param1/param2' route returns second entry and parameters array (param1, param2).

Supported storages

  • array (supports callbacks)
  • file (supports callbacks),
  • SQLite,
  • MySQL (uses main db connection from app).

Requirements

  • PHP >= 7.1

Install

Install with Composer:

composer require php-strict/simple-route

Usage

Basic usage:

use PhpStrict\SimpleRoute\Route;
use PhpStrict\SimpleRoute\ArrayStorage;

$routes = [
    '/' => [
        'title'     => 'Main page title',
        'callback'  => function () {
            return 'Main page callback result';
        },
    ],
    '/qwe' => [
        'title'     => 'Page qwe title',
        'callback'  => function () {
            return 'Page qwe callback result';
        },
    ],
    '/qwe/rty' => [
        'title'     => 'Page qwe/rty title',
    ],
    '/qwe/rty/uio' => [
        'title'     => 'Page qwe/rty/uio title',
    ],
];

$path = $_SERVER['PATH_INFO'] ?? $_SERVER['ORIG_PATH_INFO'];

$result = Route::find($path, new ArrayStorage($routes));

if (null === $result) {
    //show error or redirect to mainpage
}

/*
structure of $result for path '/qwe/param1/param2':
{
    entry: {
        key: '/qwe',
        data: [
            'title'     => 'Page qwe title',
            'callback'  => function () {
                return 'Page qwe callback result';
            }
        ]
    },
    params: ['param1', 'param2']
}
*/

//just output

echo '<h1>' . $result->entry->data['title'] . '</h1>';

if (isset($result->entry->data['callback'])) {
    echo $result->entry->data['callback']();
}

if (0 < count($result->params)) {
    echo '<ul>';
    foreach ($result->params as $param) {
        echo '<li>' . $param . '</li>';
    }
    echo '</ul>';
}

Tests

To execute the test suite, you'll need Codeception.

vendor\bin\codecept run