tbht/press

类似于nodejs/koa的框架

v0.3.0 2021-03-30 07:52 UTC

README

PHP Composer codecov

此项目是nodejs的koa框架的翻译。

安装

$ composer require tbht/press

你好 Press

use Press\Application;
use Press\Context;

$app = new Application();

$app->use(function (Context $ctx, callable $next) {
    $ctx->body = 'Hello Press';
});

$app->listen();

中间件

以下是一个logger中间件的示例

use Press\Context;
use Press\Application;

$app = new Application();

$app->use(function (Context $ctx, callable $next) {
    $start = time();
    return $next()
        ->then(function () use($start, $ctx) {
            $ms = time() - $start;
            $method = $ctx->method;
            $url = $ctx->url;

            print_r("{$method} {$url} - {$ms}ms");        
        });
});

文档

应用

hello world

use Press\Application;
use Press\Context;

$app = new Application();

$app->use(function (Context $ctx, callable $next) { 
      $ctx->body = 'Hello World';
});

$app->listen(function () {
    var_dump('final var dump');
});

// or 

$app->listen(['port' => 8080]);

级联

use Press\Application;
use Press\Context;

$app = new Application();

// logger
$app->use(function (Context $ctx, callable $next) {
    return $next()
        ->then(function () use ($ctx) {
            $rt = $ctx->response->get('x-response-time');
            $method = $ctx->method;
            $url = $ctx->url;
            echo "{$method} {$url} - {$rt}";
        });
});

// x-response-time
$app->use(function (Context $ctx, callable $next) {
    $start = time();
    return $next()
        ->then(function () use ($ctx,$start) {
            $ms = time() - $start;
            $ctx->set('x-response-time', "{$ms}ms");
        });
});

// response
$app->use(function (Context $ctx, callable $next) {
    $ctx->body = 'Hello World';
});

设置

  • $app->env 默认为 'development'

  • $app->proxy 当为true时,信任代理头字段

  • $app->subdomainOffset 忽略 .subdomains 的偏移量 [2]

$app->listen(...)

use Press\Application;

$app = new Application();

$app->listen([
    "host" => "127.0.0.1",
    "port" => 8080
]);

// or 

$app->listen(function () {
    echo "call back run";
});

$app->callback()

返回一个适合以下HTTP服务器请求的回调函数。

use React\EventLoop\Factory;

$loop = Factory::create();

$server = new React\Http\Server($loop, function (Psr\Http\Message\ServerRequestInterface $request) {
    
    // ...  

});

$app->use()

中间件 部分

$app->context

$app->contextctx 创建的原型。

$app->use(function ($ctx) { 

$ctx->db = new DB();

});

错误处理

$app->on("error", function () {

    echo "this is an error";
});

上下文