runtime/swoole-nyholm

Swoole 运行时配合 nyholm/psr7

资助包维护!
nyholm

安装: 344

依赖: 0

建议: 0

安全: 0

星星: 4

观察者: 4

分支: 0

0.2.0 2023-12-12 11:39 UTC

This package is auto-updated.

Last update: 2024-09-20 07:52:47 UTC


README

Swoole的运行时。

如果你是首次接触Symfony运行时组件,请阅读主README了解更多。

安装

composer require runtime/swoole-nyholm

用法

为你的应用程序定义环境变量 APP_RUNTIME

APP_RUNTIME=Runtime\SwooleNyholm\Runtime

纯PHP

// public/index.php

use Swoole\Http\Request;
use Swoole\Http\Response;

require_once dirname(__DIR__) . '/vendor/autoload_runtime.php';

return function () {
    return function (Request $request, Response $response) {
        $response->header("Content-Type", "text/plain");
        $response->end("Hello World\n");
    };
};

PSR

// public/index.php

use Nyholm\Psr7\Response;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

require_once dirname(__DIR__) . '/vendor/autoload_runtime.php';

class App implements RequestHandlerInterface {
    public function handle(ServerRequestInterface $request): ResponseInterface {
        $name = $request->getQueryParams()['name'] ?? 'World';
        return new Response(200, ['Server' => 'swoole-runtime'], "Hello, $name!");
    }
}

return function(): RequestHandlerInterface {
    return new App();
};

使用选项

你可以使用Symfony的运行时APP_RUNTIME_OPTIONS API定义一些配置。

// public/index.php

use App\Kernel;

$_SERVER['APP_RUNTIME_OPTIONS'] = [
    'host' => '0.0.0.0',
    'port' => 9501,
    'mode' => SWOOLE_BASE,
    'settings' => [
        'worker_num' => swoole_cpu_num() * 2,
        'enable_static_handler' => true,
        'document_root' => dirname(__DIR__) . '/public'
    ],
];

require_once dirname(__DIR__) . '/vendor/autoload_runtime.php';

return function (array $context) {
    return new Kernel($context['APP_ENV'], (bool) $context['APP_DEBUG']);
};