innmind/framework

Http/Cli 框架

2.3.0 2024-08-01 12:35 UTC

This package is auto-updated.

Last update: 2024-09-01 12:48:18 UTC


README

Build Status codecov Type Coverage

这是一个简约的 HTTP/CLI 框架,通过中间件适应简单到复杂的应用。

框架配置不可变,并使用声明式方法。

重要:要正确使用此库,您必须使用 vimeo/psalm 验证您的代码。

安装

composer require innmind/framework

用法

请查看文档以深入了解框架。

Http

第一步是创建将通过 Web 服务器(例如 public/index.php)公开的索引文件。然后您需要指定您想要处理的路由。

注意

如果您没有配置任何路由,它将响应 404 Not Found 并带有空内容。

<?php
declare(strict_types = 1);

require 'path/to/composer/autoload.php';

use Innmind\Framework\{
    Main\Http,
    Application,
};
use Innmind\Router\Route\Variables;
use Innmind\Http\{
    ServerRequest,
    Response,
    Response\StatusCode,
};
use Innmind\Filesystem\File\Content;

new class extends Http {
    protected function configure(Application $app): Application
    {
        return $app
            ->route('GET /', static fn(ServerRequest $request) => Response::of(
                StatusCode::ok,
                $request->protocolVersion(),
                null,
                Content::ofString('Hello world!'),
            ))
            ->route('GET /{name}', static fn(ServerRequest $request, Variables $variables) => Response::of(
                StatusCode::ok,
                $request->protocolVersion(),
                null,
                Content::ofString("Hello {$variables->get('name')}!"),
            ));
    }
};

您可以通过 cd public && php -S localhost:8080 运行此脚本。如果您打开 Web 浏览器,它将显示 Hello world!,如果您访问 /John,它将显示 Hello John!

Cli

您的 CLI 工具的入口点可能看起来像这样。

注意

默认情况下,如果您没有配置任何命令,它将始终显示 Hello world

<?php
declare(strict_types = 1);

require 'path/to/composer/autoload.php';

use Innmind\Framework\{
    Main\Cli,
    Application,
};
use Innmind\OperatingSystem\OperatingSystem;
use Innmind\TimeContinuum\{
    Clock,
    Earth\Format\ISO8601,
};
use Innmind\DI\Container;
use Innmind\CLI\{
    Console,
    Command,
};
use Innmind\Immutable\Str;

new class extends Cli {
    protected function configure(Application $app): Application
    {
        return $app->command(
            static fn(Container $container, OperatingSystem $os) => new class($os->clock()) implements Command {
                public function __construct(
                    private Clock $clock,
                ) {
                }

                public function __invoke(Console $console): Console
                {
                    $today = $this->clock->now()->format(new ISO8601);

                    return $console->output(Str::of("We are the: $today\n"));
                }

                public function usage(): string
                {
                    return 'today';
                }
            },
        );
    }
};

我们可以通过 php filename.php(或 php filename.php today)执行我们的脚本,并输出类似 We are the: 2022-12-30T14:04:50+00:00 的内容。