PHP code example of setono / symfony-main-request-trait

1. Go to this page and download the library: Download setono/symfony-main-request-trait library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

setono / symfony-main-request-trait example snippets




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
    }
}



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
    }
}