setono/symfony-main-request-trait

一个PHP特性,使主请求在多个Symfony版本上都能正常工作

v1.0.0 2022-06-07 13:41 UTC

This package is auto-updated.

Last update: 2024-09-15 13:11:07 UTC


README

Latest Version Software License Build Status Code Coverage Mutation testing

这是一个方便的库,用于维护Symfony组件包或使用Symfony组件的库的维护者。当Symfony在多个地方将命名从master改为main时,这导致某些方法在Symfony v5中被弃用,并在v6中被移除。

这个库将使您能够支持Symfony v4-v6,甚至不需要考虑重命名 :)

安装

composer require setono/symfony-main-request-trait

用法

使用RequestStack的示例

<?php

declare(strict_types=1);

use Setono\MainRequestTrait\MainRequestTrait;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;

final class YourService
{
    use MainRequestTrait;

    private RequestStack $requestStack;

    public function __construct(RequestStack $requestStack)
    {
        $this->requestStack = $requestStack;
    }

    public function action(): void
    {
        /**
         * This is how you get the main request from the RequestStack. No need to worry about master/main, just get it
         * @var Request|null $request
         */
        $request = $this->getMainRequestFromRequestStack($this->requestStack);

        // do something with the request
    }
}

使用事件订阅者的示例

<?php

declare(strict_types=1);

use Setono\MainRequestTrait\MainRequestTrait;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\KernelEvent;
use Symfony\Component\HttpKernel\KernelEvents;

final class YourSubscriber implements EventSubscriberInterface
{
    use MainRequestTrait;

    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::RESPONSE => 'handle'
        ];
    }

    public function handle(KernelEvent $event): void
    {
        if (!$this->isMainRequest($event)) {
            return;
        }

        // Now we know we are dealing with the main request
    }
}