gobline/router

路由组件

v3.1.0 2015-12-20 10:00 UTC

README

路由的目的在于将 URL 映射到数据数组或回调,允许将请求路由到正确的资源。在 MVC 上下文中,这通常是控制器和控制器操作。

默认捆绑了两个路由器

  • Gobline\Router\LiteralRoute (及其国际化友好的 Gobline\Router\I18n\LiteralRoute
  • Gobline\Router\PlaceHolderRoute (及其国际化友好的 Gobline\Router\I18n\PlaceHolderRoute

路由组件允许将您的 URL 翻译成多种语言,允许拥有更多 SEO 友好和用户友好的 URL。

LiteralRoute

Literal 路由用于对 URI 路径进行精确匹配。

$router = (new Gobline\Router\LiteralRoute('/user/profile')) // profile is the route name and /user/profile is the route to match
    ->setName('profile')
    ->values([
        'controller' => 'user',
        'action' => 'profile',
    ]);

I18n LiteralRoute

$router = (new Gobline\Router\LiteralRoute('/user/profile'))
    ->setName('profile')
    ->values([
        'controller' => 'user',
        'action' => 'profile',
    ])
    ->i18n([
        'fr' => '/membre/profil',
        'nl' => '/gebruiker/profiel',
    ]);

PlaceHolderRouter

$router = (new Gobline\Router\PlaceHolderRoute('/user/:id(/)(/articles/:action(/))'))
    ->setName('profile')
    ->values([
        'controller' => 'articles',
        'action' => 'list',
    ])
    ->constraints([
        'id' => '[0-9]+',
        'action' => '[a-zA-Z]+',
    ]);

I18n PlaceHolderRouter

$router = (new Gobline\Router\PlaceHolderRoute('/user/:id(/)(/articles/:action(/))'))
    ->setName('profile')
    ->values([
        'controller' => 'articles',
        'action' => 'list',
    ])
    ->constraints([
        'id' => '[0-9]+',
        'action' => '[a-zA-Z]+',
    ])
    ->i18n([
        'fr' => '/membre/:id(/)(/articles/:action(/))',
        'nl' => '/gebruiker/:id(/)(/artikelen/:action(/))',
        'placeholders' => [
            'action' => [
                'fr' => [
                    'list' => 'liste',
                ],
                'nl' => [
                    'list' => 'lijst',
                ],
            ],
        ],
    ]);

将 URL 与一系列路由匹配

$routeCollection = new Gobline\Router\RouteCollection();
$routeCollection
    ->get(new Gobline\Router\LiteralRoute(/*...*/))
    ->post(new Gobline\Router\PlaceHolderRouter(/*...*/));

$requestMatcher = new Gobline\Router\RequestMatcher($routeCollection);
$routeData = $requestMatcher->match($request); // psr-7 server request

根据路由数据生成 URL

$uriBuilder = new Gobline\Router\UriBuilder($routerCollection);

$url = $uriBuilder->makeUrl(new Gobline\Router\RouteData('profile', ['id' => 42]));

安装

您可以使用依赖管理工具 Composer 安装路由组件。运行 require 命令以解决和下载依赖项

composer require gobline/router