inphinit/teeny 问题修复 & 功能扩展

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

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

inphinit/teeny

Composer 安装命令:

composer create-project inphinit/teeny

包简介

A ready-to-use route system

关键字:

README 文档

README

Teeny route system for PHP Teeny route system for JavaScript (Node.js) Teeny route system for Golang Teeny route system for Python

Teeny route system for PHP

Teeny is a micro-route system that is really micro, supports PHP 5.3 to PHP 8, is extremely simple and ready to use.

Install using Composer

To create a new project, run:

composer create-project inphinit/teeny <project name>

Replace <project name> by your project name, example:

composer create-project inphinit/teeny blog

Download without Composer

If you are not using Composer, you can download Teeny directly from https://github.com/inphinit/teeny/releases

Apache (.htaccess)

The .htaccess will only need some adjustment if you are using it in a subfolder, you will need to change all ErrorDocument. More details at https://httpd.apache.org/docs/2.4/custom-error.html.

If the address is something like https://<domain>/, then do:

ErrorDocument 403 /index.php/RESERVED.TEENY-403.html
ErrorDocument 500 /index.php/RESERVED.TEENY-500.html

If the address is something like https://<domain>/foo/, then do:

ErrorDocument 403 /foo/index.php/RESERVED.TEENY-403.html
ErrorDocument 500 /foo/index.php/RESERVED.TEENY-500.html

If the address is something like https://<domain>/foo/bar/, then do:

ErrorDocument 403 /foo/bar/index.php/RESERVED.TEENY-403.html
ErrorDocument 500 /foo/bar/index.php/RESERVED.TEENY-500.html

NGINX

For NGINX you can use try_files, example:

location / {
    root /home/foo/bar/teeny;

    # Redirect page errors to route system
    error_page 403 /index.php/RESERVED.TEENY-403.html;
    error_page 500 /index.php/RESERVED.TEENY-500.html;

    try_files /public$uri /index.php?$query_string;

    location = / {
        try_files $uri /index.php?$query_string;
    }

    location ~ /\. {
        try_files /index.php$uri /index.php?$query_string;
    }

    location ~ \.php$ {
        # Replace with your FPM or FastCGI address
        fastcgi_pass 127.0.0.1:9000;

        fastcgi_index index.php;
        include fastcgi_params;

        set $teeny_suffix "";

        if ($uri != "/index.php") {
            set $teeny_suffix "/public";
        }

        fastcgi_param SCRIPT_FILENAME $realpath_root$teeny_suffix$fastcgi_script_name;
    }
}

Note: For FPM use fastcgi_pass unix:/var/run/php/php<version>-fpm.sock (replace <version> by PHP version in your server)

Built-in web server

You can use built-in server to facilitate the development, Teeny provides the relative static files, which will facilitate the use, example of use (navigate to project folder using cd command):

php -S localhost:8080 -t public index.php

You can edit the server.bat (Windows) or server (Linux or macOS) files to make it easier to start the project with a simple command

Windows (server.bat file)

Configure the server.bat variables according to your environment:

rem Setup PHP, php.ini and variable order
set PHP_BIN=C:\php\php.exe
set PHP_INI=C:\php\php.ini
set PHP_VAR=GPCS

rem Setup host and port
set HOST_ADDR=localhost
set HOST_PORT=9000

Once configured, you can navigate to the project folder and run the command that will start the built-in web server, example:

cd c:\projets\blog
server

Linux and macOS (server file)

Configure the ./server variables according to your environment:

# Setup PHP, php.ini and variable order
PHP_BIN=/usr/bin/php
PHP_INI=/etc/php.ini
PHP_VAR=EGPCS

# Setup host and port
HOST_ADDR=localhost
HOST_PORT=9000

Once configured, you can navigate to the project folder and run the command that will start built-in server, example:

cd ~/projets/blog
./server

API

Methods from Teeny class

Method Description
Teeny::path(): string Get current path from URL (ignores subfolders if it is located in a subfolder on your webserver)
Teeny::status([int $code]): int Get or set HTTP status code
Teeny::action($methods, string $path, mixed $callback): void Register a callback or script for a route
Teeny::setPattern(string $pattern, string $regex): void Add or replace a pattern for custom routes, like /foo/<variable1:pattern>
Teeny::handlerCodes(array $codes, mixed $callback): void Handler HTTP status code
Teeny::exec(): bool Execute application

Add and remove routes

To create a new route in index.php put like this:

$app->action('GET', '/myroute', function () {
    echo 'Test!';
});

You can use return:

$app->action('GET', '/myroute', function () {
    return 'Test!';
});

To remove a route use null value, like this:

$app->action('GET', '/myroute', null);

Route include file

To include a file uses like this:

$app->action('GET', '/myroute', 'foo/bar/test.php');

If is foo/bar/test.php not found in project will display the following error:

Warning: require(foo/bar/test.php): failed to open stream: No such file or directory in /home/user/blog/vendor/teeny.php on line 156

Fatal error: require(): Failed opening required 'foo/bar/test.php' (include_path='.') /home/user/blog/vendor/teeny.php on line 156

HTTP status

To retrieve HTTP status from SAPI (Apache, Ngnix, IIS) or previously defined in the script itself use it like this:

$var = $app->status();

To retrieve into a route use it like this:

$app->action('GET', '/myroute', function ($app) {
    echo 'HTTP status: ', $app->status();
});

To set a new HTTP status use it like this (eg.: emit 404 Not Found):

$app->status(404);

To set into route use it like this (a example with condition/if):

$app->action('GET', '/report', function ($app) {
    $file = 'data/foo.csv';

    if (is_file($file)) {
        header('Content-Type: text/csv');
        readfile($file);
        /**
         * Note: this is just an example, about sending a file,
         * if possible use "X-Sendfile" or equivalent
         */
    } else {
        $app->status(404);

        echo 'Report not found';
    }
});

Named params in route

You can use params like this:

$app->action('GET', '/user/<user>', function ($app, $params) {
    var_dump($params);
});

If you access a URL like this http://mywebsite/user/mary returns:

array(2) {
  ["user"]=>
  string(3) "mary"
}

Another example:

$app->action('GET', '/article/<name>-<id>', function ($app, $params) {
    // Only numeric IDs are valid
    if (ctype_digit($params['id'])) {
        echo 'Article ID: ', $params['id'], '<br>';
        echo 'Article name: ', $params['name'];
    } else {
        $app->status(400);

        echo 'Invalid URL';
    }
});

If you access a URL like this http://mywebsite/article/mary-1000 returns:

Article ID: 1000
Article name: mary

Supported types for named parameters in routes

An example, only numeric id are valid:

$app->action('GET', '/article/<name>-<id:num>', function ($app, $params) {
    echo 'Article ID: ', $params['id'], '<br>';
    echo 'Article name: ', $params['name'];
});
Type Example Description
alnum $app->action('GET', '/baz/<video:alnum>', ...); Only accepts parameters with alpha-numeric format and $params returns array( video => ...)
alpha $app->action('GET', '/foo/bar/<name:alpha>', ...); Only accepts parameters with alpha format and $params returns array( name => ...)
decimal $app->action('GET', '/baz/<price:decimal>', ...); Only accepts parameters with decimal format and $params returns array( price => ...)
num $app->action('GET', '/foo/<id:num>', ...); Only accepts parameters with integer format and $params returns array( id => ...)
nospace $app->action('GET', '/foo/<nospace:nospace>', ...); Accepts any characters except spaces, like white-spaces (%20), tabs (%0A) and others (see about \S in regex)
uuid $app->action('GET', '/bar/<barcode:uuid>', ...); Only accepts parameters with UUID format and $params returns array( barcode => ...)
version $app->action('GET', '/baz/<api:version>', ...); Only accepts parameters with semversion (v2) format and $params returns array( api => ...)

For add new patterns use it like this Teeny::setPattern(), examples:

$app->setPattern('example', '[A-Z]\d+');

$app->action('GET', '/custom/<myexample:example>', function ($app, $params) {
    echo '<h1>custom pattern</h1>';
    echo '<pre>';
    print_r($params);
    echo '</pre>';
});

And to access this route exemple use http://mysite/test/A00001 or http://mysite/test/C02, start with upper-case letter and after with an integer number

Dealing with large files

To work with large files you can choose to use the following server modules:

Module Server Documentation
X-Sendfile Apache https://tn123.org/mod_xsendfile/
X-Accel-Redirect NGINX https://www.nginx.com/resources/wiki/start/topics/examples/x-accel/
X-LIGHTTPD-send-file and X-Sendfile2 Lighttpd https://redmine.lighttpd.net/projects/1/wiki/X-LIGHTTPD-send-file

A simple example:

$software = $_SERVER['SERVER_SOFTWARE'];
$send = null;

if (stripos($software, 'apache') !== false) {
    $send = 'X-Sendfile';
} else if (stripos($software, 'nginx') !== false) {
    $send = 'X-Accel-Redirect';
} else if (stripos($software, 'lighttpd') !== false) {
    $send = 'X-LIGHTTPD-send-file';
}

$app->action('GET', '/download', function () use ($send) {
    $file = '/protected/iso.img';

    if ($send) {
        header($send . ': ' . $file);
        return;
    }

    $handle = fopen($file, 'rb');

    if ($handle === false) {
        $app->status(500);
        return 'Failed to read file';
    }

    // fallback (this is just an example)
    $length = 2097152;

    header('Content-Disposition: attachment; filename="iso.img"');
    header('Content-Length: ' . filesize($file));

    while (!feof($handle)) {
        echo fgets($handle, $length);
        flush();
    }

    fclose($handle);
});

Serving public files (and scripts)

To serve public files (or scripts) you must add them to the public folder. The /public/* prefix is removed from the final URL, for example, if there is a file like public/foobar.html, then the user will simply access the address https://<domain>/foobar.html.

Subfolders will also work, if it has a file like public/foo/bar/baz/video.webm then the user should go to https://<domain>/foo/bar/baz/video.webm.

You can add PHP scripts, and they will be executed normally, if you have a script like public/sample/helloworld.php, just access https://<domain>/sample/helloworld.php

If you want to make a blog available, such as Wordpress, you must also place it inside the folder, an example of structure:

├─── .htaccess
├─── index.php
├─── composer.json
├─── vendor/
└─── public/
     ├─── helloword.html
     └─── blog/
          ├─── .htaccess
          ├─── index.php
          ├─── wp-activate.php
          ├─── wp-blog-header.php
          ├─── wp-comments-post.php
          ├─── wp-config-sample.php
          ├─── wp-config.php
          ├─── wp-cron.php
          ├─── wp-links-opml.php
          ├─── wp-load.php
          ├─── wp-login.php
          ├─── wp-mail.php
          ├─── wp-settings.php
          ├─── wp-signup.php
          ├─── wp-trackback.php
          ├─── xmlrpc.php
          ├─── wp-admin/
          ├─── wp-content/
          └─── wp-includes/

You can then access the blog at https://<domain>/blog/. Other samples:

  • https://<domain>/blog/wp-admin/
  • https://<domain>/blog/2021/03/24/astronomy-messier-87-black-hole/
  • https://<domain>/blog/2023/04/17/researchers-discover-small-galaxy/

If you need more features you can experience the Inphinit PHP framework: https://inphinit.github.io/

inphinit/teeny 适用场景与选型建议

inphinit/teeny 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 396 次下载、GitHub Stars 达 9, 最近一次更新时间为 2020 年 04 月 25 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

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

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2020-04-25