alexkratky/routex 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

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

alexkratky/routex

Composer 安装命令:

composer require alexkratky/routex

包简介

The fast routing system. Easy to use.

README 文档

README

The fast routing system. Easy to use.

Installation

composer require alexkratky/routex

Introduction

This documentation is for RouteX with panx-framework. The panx-framework will autoload files etc., without that, you need to write own handler. But the usage is the same with or without panx-framework.

RouteX is default routing system of panx-framework. The documentation for RouteX is available here (Some things can be different, because the documentation is written for use with panx-framework.

Running RouteX without panx-framework

require 'vendor/autoload.php';

use AlexKratky\URL;
use AlexKratky\Route;
use AlexKratky\RouteHandler;

Route::setError(Route::ERROR_NOT_FOUND, "404.php"); // only if you want custom error 404 page
Route::set('/', 'home.php'); // set routes - URI: '/', template file: 'home.php'

$URL = new URL(); // Creates a new instance of URL object
Route::setMiddlewaresPath($_SERVER['DOCUMENT_ROOT'] . '/middlewares/'); // only if you will use middlewares
Route::setControllersPath($_SERVER['DOCUMENT_ROOT'] . '/controllers/'); // optional (faster improvement)
$template_files = Route::search($URL->getString()); // Searches in all routes and find the right template file

$rh = new RouteHandler($_SERVER['DOCUMENT_ROOT'] . '/template/', $_SERVER['DOCUMENT_ROOT'] . '/controllers/', $_SERVER['DOCUMENT_ROOT'] . '/handlers/'); // *
$rh->setHandlers([
    'latte' => 'LatteHandler'
]); // Sets custom handler for *.latte extension
$rh->handle($template_files); // includes all files or execute function

*Creates a new instance of RouteHandler

  • RouteHandler will require all files provided by Route::search()
  • The first parameter is template directory
  • The second parameter is controllers directory
  • The third parameter is handlers directory

Handlers are needed for all extension that is not .*php file. You can find more about handlers here.

Syntax

Syntax of routes:

Route::set("/URI/TO/HANDLE", "File_to_require.php");

In URI, you can use wildcards (+, *).

The + meaning is one element, for example: /post/+/edit will handle /post/1/edit, /post/2/edit, ...

The * meaning is one or more elements, for example: /post/* will handle /post/1, but also /post/1/edit, /post/2/view, ...

But in URI you can use parameters too, for example /post/{ID}/edit have same meaning as /post/+/edit, but you can access to {ID} using Route::getValue("ID").

Default routes

In /routes/ directory is also file called default.php containing default routes. In default routes are routes to error pages. For example Error 404. When you need to set route for error code (403, 404), you need to call function Route::setError instead of Route::set. Example syntax:

Route::setError(404, "default/errors/404.php");

Using wildcards

Keep in mind that routes with wildcard should be last, for example:

Route::set("/", "home.php");
Route::set("*", "test.php");

This will display home.php file to all users requesting to /, and test.php to all users requesting something difference.

But if you write something like this:

Route::set("*", "test.php");
Route::set("/", "home.php");

The result will be different. It will display test.php to all users, whatever user request. So if user tries to request /, framework will display test.php instead of home.php. So in this case, the second route is useless, and should be deleted to keep route file clear.

< action > and < controller > wildcards

These wildcards will automatically include controller and call the contoller method specified by action. For example, you will have following route

 Route::set("/admin/<controller>/<action>", "form.php");

and the user will visit with this URI: /admin/auth/login/. This will include AuthController and call the contoller's method specified by action - login() (AuthContoller::login()).

Parameters with regex rule

You can limit the route parameter by regular expression. For example, you want to use parameter {ID}, which should be just number, so you can do it by this:

Route::set("example/{ID[^[0-9]*$]}", "id.php");

If you enter something different then just ID, it will try to find other route, otherwise display 404.

Parameters with Validator rule

You can limit the route parameter by Validator rule. For example, you want to use parameter {NAME}, which should be valid name, so you can do it by this:

Route::set("/{NAME#Validator::validateUsername}");

Including multiple files

If you want to include more template files, then you need to pass array, for example:

Route::set("/docs/intro", ["header.php", "intro.php", "footer.php"]);

No files

You can leave second parameter (files or function) empty, so no files will be required, only if you set up the Controller, then will be called.

Routes with redirect

If you want to redirect from one route to another, you can do it by this:

Route::set("/docs", function() {
    redirect("/docs/intro");
});
Route::set("/docs/intro", ["header.php", "intro.php", "footer.php"]);

Routes with function

The second parameter of route can be anonymous function (Like in redirect).

Route::set("/dumpServerVariable", function() {
    echo 'This route will dump() $_SERVER variable';
    dump($_SERVER); // Function from panx
});

Locking route to method

If you need route accessible only from certain http methods, you can do it by passing third argument.

Route::set("/", "home.php", ["GET"]);

Route above will be accessible only using GET method.

Route::set("/postGet", "example.php", ["POST", "GET"]);

Route above will be accessible using methods POST and GET.

The third argument is always an array. If you visit route, that does not support that method you are requesting, you will get Error 400 - Bad request.

API routes

API routes should be in /routes/api.php file. You do not sets the route using function Route::set(), but using Route::apiGroup(). For example:

Route::apiGroup("v1", array(
    // /api/v1/list
    array("list", function(){
        echo "list";
    }),
    // /api/v1/getlatestversion/stable
    array("getlatestversion/stable", function() {
        echo "0.1";
    }, ["GET"]),
));

As the first parameter, you specify the version of API, for example v1, second parameter is array, containing all routes. Each route is single array. In route array, the first parameter is URI, the second parameter is function , file or array of files. The third parameter is optional. If you enter third parameter, it will lock route to certain http methods (See Locking route to method for more details).

Why you should use API routes instead of classic routes? If the first element in URI is /api/, it will check all API routes first, after it will check all classic routes. So it will increase the speed of response.

Route::apiGroup() function will generate route by following patern: /api/{VERSION}/{URI}, where {VERSION} is for example v1, and {URI} is for example list or getlatestversion/stable as in example above.

Controllers

You can setup controller using setController() function:

Route::set('/login', 'auth/login.latte')->setController("AuthController");

To get more info about controller, see Controllers

Middlewares

You can setup controller using setMiddleware() function:

Route::set('/verifymail/{TOKEN}', function() {
    
})->setMiddleware(['AuthMiddleware']);

The parameter must be always array, even if you set only one middleware.

To get more info about middlewares, see Middlewares

API Endpoints

You can set API endpoint using function Route::setApiEndpoint():

Route::setApiEndpoint("v3", new API("v3"));

To get more info about API endpoints, see API Endpoints

API Extended syntax

Because API route have many parameters, it is recommended to use following syntax:

Route::apiGroup("v5", array(
    array(
        "route" => "test/{name}/{action}",
        "files" => null,
        "lock" => null,
        "required_params" => null,
        "action" => "login",
        "alias" => "test"
    ),
));

Aliases

You can set up alias to each route. This is useful for your template files, because you will not write the absolute routes, e.g. '/login', but you will use the alias. If you using Latte, then you can do it by n:link, e.g. n:link="login" and when you change the route in route file, you do not need to edit the template file. In n:link, you can also include parameters for route and GET method. So if your route have wildcard, you can do it like this:

<?php
Route::set("/test/of/route/<action>/{NAME}/{ID}/*", function() {echo "Hello";});
?>

<a n:link="test, 'action=akce:jmeno:identifikator:hvezdicka=[1,10,20,30]', 'id=10:remember=true:test'">macro test</a>

<!-- which will create -->
<a href="/test/of/route/akce/jmeno/identifikator/1/10/20/30/?id=10&remember=true&test">macro test</a>

To set alias for API route, you need as 6th parameter ([5]) or by extended syntax.

Required parameters

You can set required parameters using ->setRequiredParameters(array $get, array $post);

Where the $get and $post are arrays containing the names of the inputs.

Other functions of Route class

Route::searchWithNoLimits()

This function will return template file(s)/function without limitation of middlewares etc. Works only for API routes. Used in API endpoints & caching routes.

Route::convertRoute($route = null)

Convert the URI to route.

  • For example, if you set route '/example/+/edit' in route.php and you pass the URI to this function (e.g., /example/13/edit), it will returns the route with wildcard -> '/example/+/edit'

alexkratky/routex 适用场景与选型建议

alexkratky/routex 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 61 次下载、GitHub Stars 达 1, 最近一次更新时间为 2019 年 09 月 03 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

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

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 61
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 11
  • 依赖项目数: 4
  • 推荐数: 0

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2019-09-03