承接 gabrielbull/router 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

gabrielbull/router

Composer 安装命令:

composer require gabrielbull/router

包简介

A lightning fast router for PHP

README 文档

README

Build Status Latest Stable Version Total Downloads License

Getting started

  1. PHP 5.6.x is required
  2. Install Router using Composer (recommended) or manually
  3. Setup URL rewriting so that all requests are handled by index.php
  4. (Optional) Throw in some APC for good measure

Composer Installation

  1. Get Composer
  2. Require Router with php composer.phar require gabrielbull/router
  3. Install dependencies with php composer.phar install

Example

Hello World - Obligatory hello world example

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

$router = new \Router\Router();

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

$router->dispatch();

Example 1 - Respond to all requests

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

Example 2 - Named parameters

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

Example 3 - So 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) {
        //
    }
});

Example 4 - Sending objects / files

$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");
}

Included files are run in the scope of Router ($router) so all Router methods/properties can be accessed with $this

Example file for: "controllers/projects.php"

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

Routing

[ match_type : param_name ]

Some examples

*                    // 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

Some more complicated examples

/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

Note - all routes that match the request URI are called - this allows you to incorporate complex conditional logic such as user authentication or view layouts. e.g. as a basic example, the following code will wrap other routes with a header and footer

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

Routes automatically match the entire request URI. If you need to match only a part of the request URI or use a custom regular expression, use the @ operator. If you need to negate a route, use the ! operator

// 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/', ...

Generate url

First, you have to instantiate a path generator and inject a router instance and (optionally) a domain prefix.

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

To generate an url from a route, you have to give a name to the route.

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

You can generate an url with the generate metod. The first argument is the name of the route followed by an array containing the url parameters. Finally, you can set $absolute (3rd parameter) to false to generate a relative path (default).

[ url parameters : value ]

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

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

You can add the pathGenerator into your favorite template engine and use it like this :

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

API

Below is a list of the public methods in the common classes you will most likely use. For a more formal source of class/method documentation, please see the PHPdoc generated documentation.

$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

gabrielbull/router 适用场景与选型建议

gabrielbull/router 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 355 次下载、GitHub Stars 达 3, 最近一次更新时间为 2014 年 10 月 24 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「routing」 「boilerplate」 「router」 「sinatra」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 gabrielbull/router 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 gabrielbull/router 我们能提供哪些服务?
定制开发 / 二次开发

基于 gabrielbull/router 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 355
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 3
  • 点击次数: 14
  • 依赖项目数: 4
  • 推荐数: 0

GitHub 信息

  • Stars: 3
  • Watchers: 1
  • Forks: 287
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2014-10-24