attogram/router

适用于PHP 7的Attogram Router - 小巧、灵活且功能强大

资助包维护!
attogram

v4.1.3 2020-02-15 17:00 UTC

README

欢迎来到适用于PHP 7的Attogram Router - 小巧、灵活且功能强大。

Attogram Router

Maintainability Build Status Latest Stable Version Total Downloads

Composer: composer require attogram/router

Git: git clone https://github.com/attogram/router.git

下载: https://github.com/attogram/router/archive/master.zip

许可证: MIT

示例

用法

设置URL重写。例如使用Apache .htaccess

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

创建你的 index.php。例如

use Attogram\Router\Router;

require_once('/path/to/vendor/autoload.php');

$router = new Router();

// Allow routes
$router->allow('/', 'home');
$router->allow('/foo/bar', 'foobar');
$router->allow('/pi', 3.141);
$router->allow('/hello', function () { print 'world'; });
$router->allow('/book/?/chapter/?', function (Router $router) {
    $book = $router->getVar(0);
    $chapter = $router->getVar(1);
});

// Get the $control that matches the current request
$control = $router->match();

// If no match, $control is null
if (!$control) {
    header('HTTP/1.0 404 Not Found');
    exit;
}

// Now dispatch based on $control, in whatever manner you wish

公共函数

allow

public function allow(string $route, $control)

  • 允许并设置路由的控制
  • $route = 包含URI列表的字符串,以正斜杠分隔
    • 精确路由
      • 首页: '/'
      • 页面: '/foo/bar'
        • 前导和尾随斜杠是可选的,除了顶级 '/'
    • 变量路由
      • 使用问号表示URI段为变量
      • 变量通过 $router->getVar(int $index) 获取
      • 示例
        • '/id/?' - 使用 getVar(0) 获取
        • '/book/?/chapter/?' - 使用 getVar(0)getVar(1) 获取
        • '/foo/?/?/?' - 使用 getVar(0)getVar(1)getVar(2) 获取
  • $control = 你想要的任何东西
    • 字符串、闭包、数组、对象、整数、浮点数等等!

match

public function match()

  • 获取当前请求的控制,如果没有匹配的请求则返回null

getVar

public function getVar(int $index = 0)

  • 通过索引获取URI段变量

getHome

public function getHome(): string

  • 获取安装首页的URL

getHomeFull

public function getHomeFull(): string

  • 获取包含协议和主机的安装首页URL

getCurrent

public function getCurrent(): string

  • 获取当前请求的URL

getCurrentFull

public function getCurrentFull(): string

  • 获取包含协议和主机的当前请求URL

setForceSlash

public function setForceSlash(bool $forceSlash)

  • 设置是否对所有请求强制添加尾随斜杠的选项
  • 默认为false

redirect

redirect(string $url, int $httpResponseCode = 301, bool $exitAfter = true)

  • 重定向到新URL并退出
  • 可选设置响应代码(301 = 永久,302 = 移动)

getGet

public function getGet(string $name = '')

  • 获取全局 _GET 变量,如果未找到则返回空字符串

getPost

public function getPost(string $name = '')

  • 获取全局 _POST 变量,如果未找到则返回空字符串

getServer

public function getServer(string $name = '')

  • 获取全局 _SERVER 变量,如果未找到则返回空字符串

getHost

public function getHost(): string

  • 获取当前主机名

getHostFull

public function getHostFull(): string

  • 获取当前主机名,包含协议和主机

getProtocol

public function getProtocol(): string

  • 获取当前协议:httphttps