php-strict/simple-route

简单的请求路由器。

v1.0.1 2019-12-12 08:05 UTC

This package is auto-updated.

Last update: 2024-09-12 18:51:53 UTC


README

Software License Build Status codecov Codacy Badge

简单的请求路由器。所有路由都是键/条目对。路由器寻找与键最接近的条目,并以参数数组的形式返回搜索键的剩余部分(由斜杠分割)。

它可以用来从核心模块委托执行到独立模块。每个模块都将搜索键的剩余部分作为参数数组,并按自己的方式使用它。

存储示例

<?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'],
];

对于路径'/qwe/param1/param2',路由返回第二个条目和参数数组(param1, param2)。

支持的存储

  • 数组(支持回调)
  • 文件(支持回调),
  • SQLite,
  • MySQL(使用应用程序的主数据库连接)。

要求

  • PHP >= 7.1

安装

使用Composer安装

composer require php-strict/simple-route

用法

基本用法

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>';
}

测试

要执行测试套件,您需要Codeception

vendor\bin\codecept run