定制 kenlog/route-custom 二次开发

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

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

kenlog/route-custom

Composer 安装命令:

composer require kenlog/route-custom

包简介

Route - Fast, flexible routing for PHP, enabling you to quickly and easily build RESTful web applications. This is a custom version of nezamy/route with updates for PHP 8 compatibility.

README 文档

README

Route - Fast, flexible routing for PHP, enabling you to quickly and easily build RESTful web applications.

Installation

You can download it and using it without any changes.

OR use Composer.

It's recommended that you use Composer to install Route.

$ composer require nezamy/route

Or if you looking for ready template for using this route Go to https://github.com/nezamy/just

Route requires PHP 5.4.0 or newer.

Usage

Only if using composer create index.php in root.

Create an index.php file with the following contents:

<?php
define('DS', DIRECTORY_SEPARATOR);
define('BASE_PATH', __DIR__ . DS);
//Show errors
//===================================
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
//===================================

require BASE_PATH.'vendor/autoload.php';

$app            = System\App::instance();
$app->request   = System\Request::instance();
$app->route     = System\Route::instance($app->request);

$route          = $app->route;

$route->any('/', function() {
    echo 'Hello World';
});

$route->end();

If using apache make sure the .htaccess file has exists beside index.php

How it works

Routing is done by matching a URL pattern with a callback function.

index.php

$route->any('/', function() {
    echo 'Hello World';
});

$route->any('/about', function() {
    echo 'About';
});

The callback can be any object that is callable. So you can use a regular function:

function pages() {
    echo 'Page Content';
}
$route->get('/', 'pages');

Or a class method:

class home
{
    function pages() {
        echo 'Home page Content';
    }
}
$route->get('/', ['home', 'pages']);
// OR
$home = new home;
$route->get('/', [$home, 'pages']);
// OR
$route->get('/', 'home@pages');

Method Routing

$route->any('/', function() {
    // Any method requests
});

$route->get('/', function() {
    // Only GET requests
});

$route->post('/', function() {
    // Only POST requests
});

$route->put('/', function() {
    // Only PUT requests
});

$route->patch('/', function() {
    // Only PATCH requests
});

$route->delete('/', function() {
    // Only DELETE requests
});

// You can use multiple methods. Just add _ between method names
$route->get_post('/', function() {
    // Only GET and POST requests
});

Multiple Routing (All in one)

$route->get(['/', 'index', 'home'], function() {
    // Will match 3 page in one
});

Parameters

// This example will match any page name
$route->get('/?', function($page) {
    echo "you are in $page";
});

// This example will match anything after post/ - limited to 1 argument
$route->get('/post/?', function($id) {
    // Will match anything like post/hello or post/5 ...
    // But not match /post/5/title
    echo "post id $id";
});

// more than parameters
$route->get('/post/?/?', function($id, $title) {
    echo "post id $id and title $title";
});

For “unlimited” optional parameters, you can do this:

// This example will match anything after blog/ - unlimited arguments
$route->get('/blog/*', function() {
    // [$this] instanceof ArrayObject so you can get all args by getArrayCopy()
    pre($this->getArrayCopy());
    pre($this[1]);
    pre($this[2]);
});

Named Parameters

You can specify named parameters in your routes which will be passed along to your callback function.

$route->get('/{username}/{page}', function($username, $page) {
    echo "Username $username and Page $page <br>";
    // OR
    echo "Username {$this['username']} and Page {$this['page']}";
});

Regular Expressions

You can validate the args by regular expressions.

// Validate args by regular expressions uses :(your pattern here)
$route->get('/{username}:([0-9a-z_.-]+)/post/{id}:([0-9]+)',
function($username, $id)
{
    echo "author $username post id $id";
});

// You can add named regex pattern in routes
$route->addPattern([
    'username' => '/([0-9a-z_.-]+)',
    'id' => '/([0-9]+)'
]);

// Now you can use named regex
$route->get('/{username}:username/post/{id}:id', function($username, $id) {
    echo "author $username post id $id";
});

Some named regex patterns already registered in routes

[
    'int'               => '/([0-9]+)',
    'multiInt'          => '/([0-9,]+)',
    'title'             => '/([a-z_-]+)',
    'key'               => '/([a-z0-9_]+)',
    'multiKey'          => '/([a-z0-9_,]+)',
    'isoCode2'          => '/([a-z]{2})',
    'isoCode3'          => '/([a-z]{3})',
    'multiIsoCode2'     => '/([a-z,]{2,})',
    'multiIsoCode3'     => '/([a-z,]{3,})'
]

Optional parameters

You can specify named parameters that are optional for matching by adding (?)

$route->get('/post/{title}?:title/{date}?',
function($title, $date) {
    if ($title) {
        echo "<h1>$title</h1>";
    }else{
        echo "<h1>Posts List</h1>";
    }

    if ($date) {
        echo "<small>Published $date</small>";
    }
});

Groups

$route->group('/admin', function()
{
    // /admin/
    $this->get('/', function() {
        echo 'welcome to admin panel';
    });

    // /admin/settings
    $this->get('/settings', function() {
        echo 'list of settings';
    });

    // nested group
    $this->group('/users', function()
    {
        // /admin/users
        $this->get('/', function() {
            echo 'list of users';
        });

        // /admin/users/add
        $this->get('/add', function() {
            echo 'add new user';
        });
    });

    // Anything else
    $this->any('/*', function() {
        pre("Page ( {$this->app->request->path} ) Not Found", 6);
    });
});

Groups with parameters

$route->group('/{lang}?:isoCode2', function($lang)
{
    $default = $lang;

    if (!in_array($lang, ['ar', 'en'])) {
        $default = 'en';
    }

    $this->get('/', function($lang) use($default) {
        echo "lang in request is $lang<br>";
        echo "include page_{$default}.php";
    });

    $this->get('/page/{name}/', function($lang, $name)
    {
        pre(func_get_args());
        pre($this->app->request->args);
    });
});

Middleware

$route->use(function (){
    $req = app('request');
    pre('Do something before all routes', 3);
});

$route->before('/', function (){
    pre('Do something before all routes', 4);
});

$route->before('/*!admin', function (){
    pre('Do something before all routes except admin', 4);
});

$route->before('/admin|home', function (){
    pre('Do something before admin and home only ', 4);
});

$route->after('/admin|home', function (){
    pre('Do something after admin and home only ', 4);
});

Full examples here

Support me

https://www.paypal.me/nezamy

kenlog/route-custom 适用场景与选型建议

kenlog/route-custom 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 79 次下载、GitHub Stars 达 0, 最近一次更新时间为 2024 年 03 月 03 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

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

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

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