gabrielbull/router

专为PHP设计的闪电般的路由器

0.1.7 2019-01-22 02:49 UTC

This package is auto-updated.

Last update: 2024-08-29 03:41:54 UTC


README

Build Status Latest Stable Version Total Downloads License

  • 灵活的正则表达式路由(受Sinatra启发)
  • 一套用于快速构建Web应用的样板方法
  • 几乎无开销 => 2500+ 次请求/秒

入门指南

  1. 需要PHP 5.6.x
  2. 使用 Composer(推荐)或手动安装Router
  3. 设置URL重写,使所有请求都由 index.php 处理
  4. (可选) 为了万无一失,加入一些APC

Composer安装

  1. 获取Composer
  2. 使用 php composer.phar require gabrielbull/router 安装Router
  3. 使用 php composer.phar install 安装依赖

示例

Hello World - 强制性的hello world示例

<?php
require_once __DIR__ . '/vendor/autoload.php';

$router = new \Router\Router();

$router->respond('GET', '/hello-world', function () {
    return 'Hello World!';
});

$router->dispatch();

示例 1 - 响应所有请求

$router->respond(function () {
    return 'All the things';
});

示例 2 - 命名参数

$router->respond('/[:name]', function ($request) {
    return 'Hello ' . $request->name;
});

示例 3 - 非常RESTful

$router->respond('GET', '/posts', $callback);
$router->respond('POST', '/posts', $callback);
$router->respond('PUT', '/posts/[i:id]', $callback);
$router->respond('DELETE', '/posts/[i:id]', $callback);
$router->respond('OPTIONS', null, $callback);

// To match multiple request methods:
$router->respond(array('POST','GET'), $route, $callback);

// Or you might want to handle the requests in the same place
$router->respond('/posts/[create|edit:action]?/[i:id]?', function ($request, $response) {
    switch ($request->action) {
        //
    }
});

示例 4 - 发送对象/文件

$router->respond('/report/latest', function ($request, $response) { $response->file('/tmp/cached_report.zip'); });


## Route namespaces

```php
$router->with('/users', function () use ($router) {

    $router->respond('GET', '/?', function ($request, $response) {
        // Show all users
    });

    $router->respond('GET', '/[:id]', function ($request, $response) {
        // Show a single user
    });

});

foreach(array('projects', 'posts') as $controller) {
    // Include all routes defined in a file under a given namespace
    $router->with("/$controller", "controllers/$controller.php");
}

包含的文件在Router的作用域中运行($router),因此可以使用$this访问所有Router方法和属性

示例文件: "controllers/projects.php"

// Routes to "/projects/?"
$this->respond('GET', '/?', function ($request, $response) {
    // Show all projects
});

路由

[ match_type : param_name ]

一些示例

*                    // Match all request URIs
[i]                  // Match an integer
[i:id]               // Match an integer as 'id'
[a:action]           // Match alphanumeric characters as 'action'
[h:key]              // Match hexadecimal characters as 'key'
[:action]            // Match anything up to the next / or end of the URI as 'action'
[create|edit:action] // Match either 'create' or 'edit' as 'action'
[*]                  // Catch all (lazy)
[*:trailing]         // Catch all as 'trailing' (lazy)
[**:trailing]        // Catch all (possessive - will match the rest of the URI)
.[:format]?          // Match an optional parameter 'format' - a / or . before the block is also optional

一些更复杂的示例

/posts/[*:title][i:id]     // Matches "/posts/this-is-a-title-123"
/output.[xml|json:format]? // Matches "/output", "output.xml", "output.json"
/[:controller]?/[:action]? // Matches the typical /controller/action format

注意 - 所有 匹配请求URI的路由都会被调用 - 这允许你结合复杂的条件逻辑,例如用户认证或视图布局。例如,以下代码将使用header和footer包装其他路由

$router->respond('*', function ($request, $response, $service) { $service->render('header.phtml'); });
//other routes
$router->respond('*', function ($request, $response, $service) { $service->render('footer.phtml'); });

路由自动匹配整个请求URI。如果你需要匹配请求URI的一部分或使用自定义的正则表达式,请使用 @ 操作符。如果你需要否定一个路由,请使用 ! 操作符

// Match all requests that end with '.json' or '.csv'
$router->respond('@\.(json|csv)$', ...

// Match all requests that _don't_ start with /admin
$router->respond('!@^/admin/', ...

生成url

首先,你需要实例化一个路径生成器并注入一个路由器实例和(可选)域名前缀。

$router = new \Router\Router();
$pathGenerator = new \Router\PathGenerator($router, 'http://www.domain.com');

要从路由生成URL,你必须给路由命名。

$this->respond('GET', '/route/[:foo]', function ($request, $response) {
    // Handling route here
})->setName('packageName:routeName');

你可以使用 generate 方法生成URL。第一个参数是路由的名称,然后是一个包含URL参数的数组。最后,你可以将 $absolute(《第3个参数》)设置为false以生成相对路径(默认)。

[ url parameters : value ]

$pathGenerator->generate('packageName:routeName', [
    'foo' => 'bar',
], true);

// return : http://www.domain.com/bar

你可以将 pathGenerator 添加到你的首选模板引擎中,并像这样使用它

{{ path.generate('homepage') }}

API

以下是在你可能会使用的常见类中的公共方法列表。有关更正式的类/方法文档,请参阅PHPdoc生成的文档

$request->
    id($hash = true)                    // Get a unique ID for the request
    paramsGet()                         // Return the GET parameter collection
    paramsPost()                        // Return the POST parameter collection
    paramsNamed()                       // Return the named parameter collection
    cookies()                           // Return the cookies collection
    server()                            // Return the server collection
    headers()                           // Return the headers collection
    files()                             // Return the files collection
    body()                              // Get the request body
    params()                            // Return all parameters
    params($mask = null)                // Return all parameters that match the mask array - extract() friendly
    param($key, $default = null)        // Get a request parameter (get, post, named)
    isSecure()                          // Was the request sent via HTTPS?
    ip()                                // Get the request IP
    userAgent()                         // Get the request user agent
    uri()                               // Get the request URI
    pathname()                          // Get the request pathname
    method()                            // Get the request method
    method($method)                     // Check if the request method is $method, i.e. method('post') => true
    query($key, $value = null)          // Get, add to, or modify the current query string
    <param>                             // Get / Set (if assigned a value) a request parameter

$response->
    protocolVersion($protocol_version = null)       // Get the protocol version, or set it to the passed value
    body($body = null)                              // Get the response body's content, or set it to the passed value
    status()                                        // Get the response's status object
    headers()                                       // Return the headers collection
    cookies()                                       // Return the cookies collection
    code($code = null)                              // Return the HTTP response code, or set it to the passed value
    prepend($content)                               // Prepend a string to the response body
    append($content)                                // Append a string to the response body
    isLocked()                                      // Check if the response is locked
    requireUnlocked()                               // Require that a response is unlocked
    lock()                                          // Lock the response from further modification
    unlock()                                        // Unlock the response
    sendHeaders($override = false)                  // Send the HTTP response headers
    sendCookies($override = false)                  // Send the HTTP response cookies
    sendBody()                                      // Send the response body's content
    send()                                          // Send the response and lock it
    isSent()                                        // Check if the response has been sent
    chunk($str = null)                              // Enable response chunking (see the wiki)
    header($key, $value = null)                     // Set a response header
    cookie($key, $value = null, $expiry = null)     // Set a cookie
    cookie($key, null)                              // Remove a cookie
    noCache()                                       // Tell the browser not to cache the response
    redirect($url, $code = 302)                     // Redirect to the specified URL
    dump($obj)                                      // Dump an object
    file($path, $filename = null)                   // Send a file
    json($object, $jsonp_prefix = null)             // Send an object as JSON or JSONP by providing padding prefix