buzzingpixel/corbomite-http

This package is auto-updated.

Last update: 2024-08-29 04:54:34 UTC


README

BuzzingPixel的Corbomite项目的一部分。

提供响应HTTP请求的轻量级框架。

使用方法

在你的HTTP前端控制器中,使用依赖注入器调用内核(请注意,APP_BASE_PATH 可以作为一个常量定义,必须是你供应商目录所在的位置。否则,供应商目录的路径将被自动计算)。

<?php
declare(strict_types=1);

use corbomite\di\Di;
use corbomite\http\Kernel as HttpKernel;

require __DIR__ . '/vendor/autoload.php';

Di::get(HttpKernel::class)();

内核方法参数

内核可以接收最多两个参数。

如果第一个参数是一个数组,第二个参数将被忽略,并且第一个参数作为一个数组,其值必须是实现 \Psr\Http\Server\MiddlewareInterface 的类名或类实例。这些类将在添加任何错误处理程序之后(如果未禁用CSRF中间件,则在CSRF中间件之后)以及Corbomite HTTP的Action参数和路由之前添加到中间件堆栈。

如果第一个参数是字符串或类,它必须实现 \Psr\Http\Server\MiddlewareInterface,并且如果环境变量 DEV_MODE 未设置为字符串 true,则将其添加为错误处理程序。然后,第二个参数可以是一个中间件数组,如上所述。

错误处理

如果环境变量 DEV_MODE 设置为字符串 true,内核将尝试将PHP错误输出设置为最大值,并将 \Franzl\Middleware\Whoops\WhoopsMiddleware 添加到中间件堆栈的第一个项目。这样,当遇到错误时,你可以在开发过程中获取HTTP堆栈所需的所有信息和跟踪。

如果不在开发模式下,并且你已提供上述描述的错误处理中间件,则你提供的错误中间件将首先添加到中间件堆栈中。这样,你就有机会在生产环境中渲染错误页面。

如果你发送一个字符串类名,内核将尝试从提供的 ContainerInterface 实现中获取类,如果失败,则通过 new 创建类。

以下是一个错误处理程序中间件类的示例

<?php
declare(strict_types=1);

namespace src\app\http;

use Throwable;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use some\name\space\RenderErrorPageAction;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use corbomite\http\exceptions\Http404Exception;

class ErrorPages implements MiddlewareInterface
{
    private $renderErrorPage;

    public function __construct(RenderErrorPageAction $renderErrorPage)
    {
        $this->renderErrorPage = $renderErrorPage;
    }

    public function process(
        ServerRequestInterface $request,
        RequestHandlerInterface $handler
    ): ResponseInterface {
        try {
            return $handler->handle($request);
        } catch (Throwable $e) {
            $code = 500;

            if ($e instanceof Http404Exception ||
                $e->getPrevious() instanceof Http404Exception
            ) {
                $code = 404;
            }

            return ($this->renderErrorPage)($code);
        }
    }
}

CSRF保护

默认情况下,Corbomite HTTP将 CSRF PSR-15 中间件 添加到中间件堆栈,以防止POST请求上的跨站请求伪造。

有时,可能希望某些部分免于CSRF中间件。如果您希望为某些部分禁用中间件,可以在composer.json的extra对象中定义禁用段配置。

{
    "name": "my/app",
    "extra": {
        "corbomiteHttpConfig": {
            "csrfExemptSegments": [
                "my-segment",
                "segment"
            ]
        }
    }
}

您也可以在JSON extra对象中完全禁用中间件

{
    "name": "my/app",
    "extra": {
        "corbomiteHttpConfig": {
            "disableCsrfMiddleware": true
        }
    }
}

或者,您可以在开发模式下禁用它

{
    "name": "my/app",
    "extra": {
        "corbomiteHttpConfig": {
            "disableCsrfMiddlewareDevMode": true
        }
    }
}

路由

Corbomite HTTP使用 FastRoute 进行路由。您的应用程序或任何composer包可以通过在composer.json的extra对象中提供httpRouteConfigFilePath来注册路由。

{
    "name": "my/app",
    "extra": {
        "httpRouteConfigFilePath": "src/routes.php"
    }
}

被调用的路由文件将有一个名为 $routeCollector 的变量(如果您喜欢简洁,也可以使用快捷变量 $r)。以下是一个路由文件的示例

<?php
declare(strict_types=1);

/** @var \FastRoute\RouteCollector $r */
/** @var \FastRoute\RouteCollector $routeCollector */

$routeCollector->get(
    '/my/route',
    \someclass\implementing\MiddlewareInterface::class // Must have __invoke() method
);

$routeCollector->get('/another/route', \someclass\Thing::class);

ActionParams

操作参数可以作为查询参数在 /some-uri?action=myAction 上提供,用于 get 请求,或者作为 post 请求的请求体参数 action=someAction

操作在路由之前处理,非常适合处理例如 post 请求。如果 post 请求未验证,则路由将继续处理。如果 post 请求已验证,可以重定向到新页面或返回某种类型的响应。

为了请求操作,需要设置操作配置。您的应用或任何 composer 包都可以在 composer.json 的 extra 对象中定义一个操作参数配置文件,使用 httpActionConfigFilePath 键。

{
    "name": "vendor/name",
    "extra": {
        "httpActionConfigFilePath": "src/actionConfig.php"
    }
}

操作配置文件应返回一个类似以下格式的操作数组

<?php
declare(strict_types=1);

return [
    'myAction' => [
        'class' => \some\name\space\MyClass::class,
        'method' => 'myMethod', // Or defaults to __invoke()
    ],
    'anotherAction' => [
        'class' => \some\name\space\AnotherClass::class
    ],
    'moreAction' => \some\name\space\AnotherClass::class,
];

禁用操作参数

您也可以在 JSON extra 对象中完全禁用操作参数,如下所示

{
    "name": "my/app",
    "extra": {
        "corbomiteHttpConfig": {
            "disableActionParamMiddleware": true
        }
    }
}

Twig 扩展

Corbomite HTTP 提供了一个 Twig 扩展。如果您使用 Corbomite Twig,此扩展将自动加载。否则,您可以将其添加到自己的 Twig 实例中,使用以下方式调用 Twig 的 addExtension() 方法

<?php
declare(strict_types=1);

use Twig\Environment;
use Twig\Loader\FilesystemLoader;
use corbomite\http\HttpTwigExtension;

$twig = new Environment(new FilesystemLoader('/path/to/templates'), [
    'debug' => true,
    'cache' => '/path/to/cache',
    'strict_variables' => true,
]);

$twig->addExtension(new HttpTwigExtension());

{{ throwHttpError() }}

此 Twig 函数用于从 Twig 抛出 HTTP 错误。默认情况下会抛出 404 异常。传递 500 作为参数将抛出 500 内部服务器错误。

{{ getCsrfFormKey() }}

获取 CSRF 令牌的表单键名。

{{ generateCsrfToken() }}

生成并输出 CSRF 令牌。

{{ getCsrfInput() }}

输出 CSRF 令牌的隐藏输入。

许可证

版权所有 2019 BuzzingPixel, LLC

根据 Apache License 2.0(“许可证”)许可;除非遵守许可证,否则不得使用此文件。您可以在 https://apache.ac.cn/licenses/LICENSE-2.0 获取许可证副本。

除非适用法律要求或书面同意,否则根据许可证分发的软件按“原样”基础分发,不提供任何明示或暗示的保证。有关许可证的具体语言规定权限和限制,请参阅许可证。