定制 bayfrontmedia/route-it 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

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

bayfrontmedia/route-it

Composer 安装命令:

composer require bayfrontmedia/route-it

包简介

A fast, flexible router which can be used to quickly build RESTful web apps.

README 文档

README

A fast, flexible router which can be used to quickly build RESTful web apps.

License

This project is open source and available under the MIT License.

Author

Bayfront Media

Requirements

  • PHP ^8.0 (Tested up to 8.4)
  • ctype PHP extension

Installation

composer require bayfrontmedia/route-it

Usage

Start using Route It

Default options:

use Bayfront\RouteIt\Router;

$options = [
    'automapping_enabled' => false,
    'automapping_namespace' => '',
    'automapping_route_prefix' => '',
    'class_namespace' => '',
    'files_root_path' => '',
    'force_lowercase_url' => false
];

$router = new Router($options);

Force lowercase

When force_lowercase_url is enabled in the $options array, all incoming requests which contain uppercase characters will be redirected via a 301 redirect to their lowercase counterpart. Query parameters will not be affected.

Automapping

When automapping is enabled, Route It will automatically attempt to dispatch the incoming request in the form of class/method/optional-parameter without having to define each individual route.

The incoming request must match the automapping route prefix, and classes must exist in the automapping namespace as defined in the $options array.

For example:

use Bayfront\RouteIt\Router;

$options = [
    'automapping_enabled' => true,
    'automapping_namespace' => 'App\\Pages',
    'automapping_route_prefix' => '/app'
];

$router = new Router($options);

Using the above example, incoming requests would be automapped like so:

Endpoint Class Method Parameter
/app App\Pages\Home index
/app/customers App\Pages\Customers index
/app/customers/edit App\Pages\Customers edit
/app/customers/edit/5 App\Pages\Customers edit ['id' => 5]

Understandably, automapping does not provide a solution for every scenario, in which case, routes can be added.

Named routes

Named routes are helpful when using hyperlinks in controllers, views or templates. By referencing a named route instead of a specific URL, the hyperlink will stay up-to-date with your defined routes.

When dispatching a request using the dispatch , dispatchTo, or dispatchToFallback methods, Route It will automatically insert an array of all named routes to the destination as a parameter with the key of routes, unless otherwise specified.

See documentation for these methods for more information.

Wildcards

Wildcards can be used when defining a route in order to dynamically define a path, and send its value to the destination as a parameter. The syntax is {type:name}, where type is the wildcard type, and name is the name of the parameter which is to be passed to the destination.

Wildcards include:

  • *: Any non-whitespace character in this segment of the request
  • alpha: Any alphabetic characters in this segment of the request (see ctype_alpha)
  • num: Any numeric characters in this segment of the request (see ctype_digit)
  • alphanum: Any alphanumeric characters in this segment of the request (see ctype_alnum)
  • **: Everything else that may exist on the request path (catch-all)
  • ?: Optionally existing in this segment of the request (can only be used at the last segment)

For examples, see addRoute.

Public methods

setHost

Description:

Sets the hostname for defined routes.

Parameters:

  • $host (string)

Returns:

  • (self)

Example:

$router->setHost('example.com');

$router->addRoute('GET', '/login', function () {
 
    // Destination for example.com/login

});

$router->setHost('subdomain.example.com');

$router->addRoute('GET', '/login', function () {
 
    // Destination for subdomain.example.com/login

});

getHost

Description:

Retrieves the hostname for defined routes.

Parameters:

  • None

Returns:

  • (string)

setRoutePrefix

Description:

Sets the route prefix for defined routes.

Parameters:

  • $prefix (string)

Returns:

  • (self)

Example:

$router->setHost('example.com')->setRoutePrefix('app');

$router->addRoute('GET', '/login', function () {
 
    // Destination for example.com/app/login

});

getRoutePrefix

Description:

Retrieves the route prefix for defined routes.

Parameters:

  • None

Returns:

  • (string)

addFallback

Description:

Adds a fallback destination for given request method(s) when no route can be found. The response will be sent with a 404 HTTP status code.

Parameters:

  • $methods (string|array): Request method(s) for which this fallback is valid, or "ANY"
  • $destination (mixed)
  • $params = [] (array): Parameters to pass to the destination

Returns:

  • (self)

Example:

$router->addFallback('ANY', function () {
    echo '404 page not found';
});

For more destination examples, see addRoute.

getFallbacks

Description:

Returns array of defined fallbacks.

Parameters:

  • None

Returns:

  • (array)

addRedirect

Description:

Adds a redirect. Wildcards can be used in the path.

Parameters:

  • $methods (string|array): Request method(s) for which this redirect is valid, or "ANY"
  • $path (string): Request path
  • $destination (string): Can be an internal path or fully qualified URL
  • $status = 302 (int): HTTP status code used with the redirect

Returns:

  • (self)

Example:

// Internal temporary redirect (will not redirect to self)

$router->addRedirect('ANY', '{**:path}', '/under-construction', 302);

// Fully qualified URL

$router->addRedirect('GET', '/documentation', 'https://www.example.com/new-documentation');

For more path definition examples, see addRoute.

getRedirects

Description:

Returns array of defined redirects.

Parameters:

  • None

Returns:

  • (array)

addRoute

Description:

Adds a defined route. Wildcards can be used in the path.

Destinations can be a callable function, a named route, a file, or a $class->method(). Each route can have its own predefined parameter(s), and parameters can also be defined dynamically by a "wildcard".

Parameters:

  • $methods (string|array): Request method(s) for which this route is valid, or "ANY"
  • $path (string): Request path
  • $destination (mixed)
  • $params = [] (array): Parameters to pass to the destination
  • $name = NULL (string|null): An optional name to assign to this route

NOTE: Names should not be assigned to routes which include wildcards in the path. Named routes are only intended to define specific URL's. Named route names must be unique, as names which already exist are overwritten.

Returns:

  • (self)

Example:

$router

    // Callable

    ->addRoute('GET', '/customers', function () {

        echo 'Customers';

    })

    // Callable with a wildcard parameter

    ->addRoute('GET', '/customers/{num:id}', function ($params) {

        echo 'Customer id: ' . $params['id'];

    })

    // Callable with optional wildcard (if existing in the request path, it will overwrite the defined parameter)

    ->addRoute('GET', '/optional/{?:name}', function ($params) {

        echo 'Hello, ' . $params['name'] . '! This is a callable with an optional parameter.';

    }, [
        'name' => 'John'
    ])

    // Callable, saving as a named route

    ->addRoute('GET', '/login', function($params) {

        // Login

    }, [], 'login')

    // To a named route

    ->addRoute('GET', '/oldlogin', 'login')

    // To a file from the files_root_path as defined in the options array

    ->addRoute('GET', '/file', '@filename.html')

    // To a class:method from the class_namespace as defined in the options array

    ->addRoute('GET', '/class', 'TestClass:index', ['greeting' => 'Hello!']);

any

Description:

Adds route for ANY request method.

Equivalent of calling addRoute('ANY'...)

Parameters:

  • $path (string): Request path
  • $destination (mixed)
  • $params = [] (array): Parameters to pass to the destination
  • $name = NULL (string|null): An optional name to assign to this route

NOTE: Names should not be assigned to routes which include wildcards in the path. Named routes are only intended to define specific URL's.

Returns:

  • (self)

Example:

$router->any('/customers', 'Controller:anyMethod');

connect

Description:

Adds route for CONNECT request method.

Equivalent of calling addRoute('CONNECT'...)

Parameters:

  • $path (string): Request path
  • $destination (mixed)
  • $params = [] (array): Parameters to pass to the destination
  • $name = NULL (string|null): An optional name to assign to this route

NOTE: Names should not be assigned to routes which include wildcards in the path. Named routes are only intended to define specific URL's.

Returns:

  • (self)

Example:

$router->connect('/customers', 'Controller:connectMethod');

delete

Description:

Adds route for DELETE request method.

Equivalent of calling addRoute('DELETE'...)

Parameters:

  • $path (string): Request path
  • $destination (mixed)
  • $params = [] (array): Parameters to pass to the destination
  • $name = NULL (string|null): An optional name to assign to this route

NOTE: Names should not be assigned to routes which include wildcards in the path. Named routes are only intended to define specific URL's.

Returns:

  • (self)

Example:

$router->delete('/customers', 'Controller:deleteMethod');

get

Description:

Adds route for GET request method.

Equivalent of calling addRoute('GET'...)

Parameters:

  • $path (string): Request path
  • $destination (mixed)
  • $params = [] (array): Parameters to pass to the destination
  • $name = NULL (string|null): An optional name to assign to this route

NOTE: Names should not be assigned to routes which include wildcards in the path. Named routes are only intended to define specific URL's.

Returns:

  • (self)

Example:

$router->get('/customers', 'Controller:getMethod');

head

Description:

Adds route for HEAD request method.

Equivalent of calling addRoute('HEAD'...)

Parameters:

  • $path (string): Request path
  • $destination (mixed)
  • $params = [] (array): Parameters to pass to the destination
  • $name = NULL (string|null): An optional name to assign to this route

NOTE: Names should not be assigned to routes which include wildcards in the path. Named routes are only intended to define specific URL's.

Returns:

  • (self)

Example:

$router->head('/customers', 'Controller:headMethod');

options

Description:

Adds route for OPTIONS request method.

Equivalent of calling addRoute('OPTIONS'...)

Parameters:

  • $path (string): Request path
  • $destination (mixed)
  • $params = [] (array): Parameters to pass to the destination
  • $name = NULL (string|null): An optional name to assign to this route

NOTE: Names should not be assigned to routes which include wildcards in the path. Named routes are only intended to define specific URL's.

Returns:

  • (self)

Example:

$router->options('/customers', 'Controller:optionsMethod');

patch

Description:

Adds route for PATCH request method.

Equivalent of calling addRoute('PATCH'...)

Parameters:

  • $path (string): Request path
  • $destination (mixed)
  • $params = [] (array): Parameters to pass to the destination
  • $name = NULL (string|null): An optional name to assign to this route

NOTE: Names should not be assigned to routes which include wildcards in the path. Named routes are only intended to define specific URL's.

Returns:

  • (self)

Example:

$router->patch('/customers', 'Controller:patchMethod');

post

Description:

Adds route for POST request method.

Equivalent of calling addRoute('POST'...)

Parameters:

  • $path (string): Request path
  • $destination (mixed)
  • $params = [] (array): Parameters to pass to the destination
  • $name = NULL (string|null): An optional name to assign to this route

NOTE: Names should not be assigned to routes which include wildcards in the path. Named routes are only intended to define specific URL's.

Returns:

  • (self)

Example:

$router->post('/customers', 'Controller:postMethod');

put

Description:

Adds route for PUT request method.

Equivalent of calling addRoute('PUT'...)

Parameters:

  • $path (string): Request path
  • $destination (mixed)
  • $params = [] (array): Parameters to pass to the destination
  • $name = NULL (string|null): An optional name to assign to this route

NOTE: Names should not be assigned to routes which include wildcards in the path. Named routes are only intended to define specific URL's.

Returns:

  • (self)

Example:

$router->put('/customers', 'Controller:putMethod');

trace

Description:

Adds route for TRACE request method.

Equivalent of calling addRoute('TRACE'...)

Parameters:

  • $path (string): Request path
  • $destination (mixed)
  • $params = [] (array): Parameters to pass to the destination
  • $name = NULL (string|null): An optional name to assign to this route

NOTE: Names should not be assigned to routes which include wildcards in the path. Named routes are only intended to define specific URL's.

Returns:

  • (self)

Example:

$router->trace('/customers', 'Controller:traceMethod');

getRoutes

Description:

Returns array of defined routes.

Parameters:

  • None

Returns:

  • (array)

addNamedRoute

Description:

Adds a specific path as a named route.

This is helpful when wanting to reference a URL that is not defined as a route.

Parameters:

  • $path (string): Request path
  • $name (string): Name to assign to this route

Returns:

  • (self)

Example:

$router->setHost('example.com')->setPrefix('app');

$router->addNamedRoute('/assets/css', 'css');

// Returns: https://example.com/app/assets/css
echo $router->getNamedRoute('login'); 

getNamedRoutes

Description:

Returns array of named routes.

Automatically replaces wildcards with resolved parameters.

Parameters:

  • $params = [] (array): Additional parameters used to replace wildcards in the named route

Returns:

  • (array)

getNamedRoute

Description:

Returns URL of a named route.

Automatically replaces wildcards with resolved parameters.

Parameters:

  • $name (string)
  • $default = '' (string): Default value to return if named route does not exist
  • $params = [] (array): Additional parameters used to replace wildcards in the named route

Returns:

  • (string)

resolve

Description:

Resolves the incoming HTTP request by searching for a matching redirect, route, automapped location, or fallback. Destination-specific parameters will overwrite global parameters of the same key.

The returned array consists of the following keys:

  • type
  • destination
  • status (HTTP status code)
  • params (Array)

The destination will vary based on the type:

type destination
redirect URL
route Defined route
automap Class:method
fallback Defined callback

A DispatchException will be thrown if the request is unable to be resolved.

Parameters:

  • $params = [] (array): Global parameters to pass to all destinations

Returns:

  • (array)

dispatch

Description:

Resolves and dispatches the incoming HTTP request.

Destination-specific parameters will overwrite global parameters of the same key.

Parameters:

  • $params = [] (array): Global parameters to pass to all destinations

Returns:

  • (mixed)

Throws:

  • Bayfront\RouteIt\DispatchException

Example:

use Bayfront\RouteIt\DispatchException;
use Bayfront\RouteIt\Router;

$options = [
    'automapping_enabled' => false,
    'automapping_namespace' => '',
    'automapping_route_prefix' => '',
    'class_namespace' => '',
    'files_root_path' => '',
    'force_lowercase_url' => false
];

$router = new Router($options);

// Add routes here

try {

    $router->dispatch();

} catch (DispatchException $e) {
    die($e->getMessage());
}

dispatchTo

Description:

Dispatches to a specific destination.

Destinations can be a callable function, a named route, a file, or a $class->method().

Parameters:

  • $destination (mixed)
  • $params = [] (array): Parameters to pass to the destination

Returns:

  • (mixed)

Throws:

  • Bayfront\RouteIt\DispatchException

Example:

try {

    $router->dispatchTo('TestClass:index');

} catch (DispatchException $e) {
    die($e->getMessage());
}

dispatchToFallback

Description:

Dispatches to fallback for current request method, or throws exception.

Fallback-specific parameters defined using the addFallback method will overwrite these parameters of the same key.

Parameters:

  • $params = [] (array): Parameters to pass to the destination

Returns:

  • (mixed)

Throws:

  • Bayfront\RouteIt\DispatchException

Example:

try {

    $router->dispatchToFallback();

} catch (DispatchException $e) {
    die($e->getMessage());
}

redirect

Description:

Redirects to a given URL using a given status code.

Parameters:

  • $url (string): Fully qualified URL
  • $status = 302: HTTP status code to return

Returns:

  • (void)

Throws:

  • Bayfront\RouteIt\DispatchException

Example:

try {

    $router->redirect('https://www.example.com);

} catch (DispatchException $e) {
    die($e->getMessage());
}

getResolvedParameters

Description:

Get array of all parameters present for the current route once resolved/dispatched.

Parameters:

  • None

Returns:

  • (array)

bayfrontmedia/route-it 适用场景与选型建议

bayfrontmedia/route-it 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1.36k 次下载、GitHub Stars 达 1, 最近一次更新时间为 2020 年 08 月 22 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

围绕 bayfrontmedia/route-it 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 1.36k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 10
  • 依赖项目数: 2
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2020-08-22