php-strict / simple-route
Simple request router.
v1.0.1
2019-12-12 08:05 UTC
Requires
- php: ^7.1
Requires (Dev)
- codeception/codeception: ^2.5.1
This package is auto-updated.
Last update: 2024-10-12 19:01:36 UTC
README
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