p810/router

通过一个入口点响应对您应用程序中请求的任何URI。

1.1.2 2018-07-20 21:45 UTC

This package is auto-updated.

Last update: 2024-09-09 13:39:42 UTC


README

通过一个入口点响应对您应用程序中请求的任何URI。

安装

composer require p810/router

用法

路由是您希望应用程序响应的任何URI。路由必须包含在RouteCollection实例中。路由可以通过RouteCollection::match()进行检查,这要么抛出异常(UnmatchedRouteException),要么调用指定的回调。

注意,为了使用此功能,您必须配置您的Web服务器将请求定向到放置此代码的脚本(例如,Apache的.htaccess)。

加载控制器

您可以通过调用Collection::setControllerNamespace()设置一个默认命名空间来加载类。只需告诉它控制器的基础命名空间。

$router->setControllerNamespace('MyApp\\Controllers\\');

动态路由

您可以通过以下令牌之一将参数传递到路由中。

您可以通过在闭合括号前加一个问号来指定一个令牌是可选的,如下所示:{token?}

示例

<?php

require_once dirname(__FILE__) . '/vendor/autoload.php';

/**
 * Create a collection and register a route to it.
 */

use p810\Router\UnmatchedRouteException;
use p810\Router\Collection as RouteCollection;

$router = new RouteCollection;

$router->register('/', function () {
    return 'Hello world!'; 
});

$router->register('/{word}', function ($name) {
    return sprintf('Hello %s, how are you today?', $name); 
});


/**
 * Attempt to match the route based on the current URI.
 *
 * The returned result will then be output.
 */

try {
    $result = $router->match( $_SERVER['REQUEST_URI'] );
} catch (UnmatchedRouteException $e) {
    http_response_code(404);

    $result = 'The requested resource could not be found!';
}

print $result;