ivanstan / symfony-extend-request
Adds ability to extend Symfony request class and use child class as controller method parameter type
Installs: 2
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 1
Forks: 0
Open Issues: 0
Type:symfony-bundle
Requires
- php: >=8.0
- symfony/framework-bundle: ^4.0|5.0|^6.0
- symfony/yaml: ^4.0|5.0|^6.0
Requires (Dev)
- phpunit/php-code-coverage: ^9.2
- phpunit/phpunit: ^9
- symfony/test-pack: ^1.0
This package is auto-updated.
Last update: 2024-10-17 15:29:16 UTC
README
This bundle allows users to annotate the controller method type with class that
extends Symfony\Component\HttpFoundation\Request
and implement custom logic inside child class.
Example
use App\Request\ExtendedRequest; class ProductsController extends AbstractController { #[Route('product/search')] public function search(SearchProductsRequest $request): JsonResponse { return new JsonResponse([ 'name' => $request->getName(), ]); } }
namespace App\Request; use Symfony\Component\HttpFoundation\Request; class SearchProductsRequest extends Request { public function getName(): string { return $this->get('name'); } }
Installation
composer require ivanstan/symfony-extend-request
Add to your project's bundle.php
:
<?php return [ Ivanstan\SymfonyExtendRequest\SymfonyExtendRequestBundle::class => ['all' => true], ];
Requests as services
Classes extending Symfony\Component\HttpFoundation\Request
can now be promoted to fully functional
Symfony services, with all of its dependency injection features. Since request constructor is dedicated for
query params, headers, etc. Required
attribute is encouraged to inject other services in extended request class, for example:
<?php namespace App\Request; use Psr\Log\LoggerInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Contracts\Service\Attribute\Required; class ExtendedRequest extends Request { protected LoggerInterface $logger; #[Required] public function setLogger(LoggerInterface $logger):void { $this->logger = $logger; } }
This will de-facto work if autowiring is enabled.
Testing
Run: composer test
Next development steps
- Support request validation in child classes.