tonis/router

此包已被弃用且不再维护。未建议替代包。

Tonis\Router 是一个轻量级、HHVM 兼容且无依赖的路由库。

dev-master / 1.0.x-dev 2015-06-17 14:25 UTC

This package is not auto-updated.

Last update: 2022-02-01 12:48:06 UTC


README

Build Status Code Coverage Scrutinizer Code Quality

安装

可以使用 composer 安装 Tonis\Router,它将为您设置任何自动加载。

composer require tonis-io/router

此外,您可以下载或克隆仓库并设置自己的自动加载。

添加路由

use Tonis\Router\Router;

$router = new Router();

// Basic route with name
$router->add('foo', '/foo');
// matches /foo

// Basic route with no name
$router->add(null, '/foo');
// matches /foo

// Route with tokens
$router->add('foo', '/foo/{name}');
// matches /foo/bar

// Router with optional tokens
$router->add('foo', '/foo{/name?}');
// matches /foo or /foo/bar

// Router with tokens and constraints
$router->add('foo', '/foo/{id:\d+}-{slug}');
// matches /foo/1-bar but not /foo/baz-bar

// The kitchen sink
$router->add('foo', '/foo/{id:\d+}{-slug?:[a-zA-Z-_]+}');
// matches /foo/1, /foo/1-bar, /foo/1-BaR
// does not match /foo/1-2

将命名路由组装成 URL

use Tonis\Router\Router;

$router = new Router();
$router->add('foo', '/foo');

// outputs '/foo'
echo $router->assemble('foo');

$router->add('foo', '/foo/{id:\d+}{-slug?:[a-zA-Z-_]+}');

// outputs '/foo/1'
echo $router->assemble('foo', ['id' => 1]);

// outputs '/foo/1-bar'
echo $router->assemble('foo', ['id' => 1, 'slug' => 'bar']);

匹配路由

use Tonis\Router\Router;

$router = new Router();
$router->add('foo', '/foo');

// result is NULL
echo $router->match('/bar');

// result is an instance of Tonis\Router\Match
$match = $router->match('/foo');

// output is 'foo'
echo $match->getName();

$router->add('bar', '/bar/{id}');

// result is an instance of Tonis\Router\Match
$match = $router->match('/bar/1');

// output is 'bar'
echo $match->getName();

// output is '1'
echo $match->get('id');

// you can also have defaults for params that may not exist (output is 'foo')
echo $match->get('does-not-exist', 'foo');

默认路由参数

use Tonis\Router\Router;

$router = new Router();
$router->add('foo', '/foo{/id?}', ['defaults' => ['id' => 1, 'controller' => 'foo-controller']]);

$match = $router->match('/foo/1234');

// output is '1234'
echo $match->get('id');

$match = $router->match('/foo');

// output is '1'
echo $match->get('id');

// output is 'foo-controller'
echo $match->get('controller');