Cannot autowire argument $request

1k views Asked by At

My controller looks like:

use Psr\Http\Message\ServerRequestInterface;

class HelloController extends AbstractController
{
    public function __invoke(ServerRequestInterface $request): Response
    {
        dd($request)
        return $this->json([]);
    }

After going to URL of this controller I get the following error:

Cannot autowire argument $request of "HelloController()": it references interface "Psr\Http\Message\ServerRequestInterface" but no such service exists. Did you create a class that implements this interface?

My composer.json looks like:

{
    "type": "project",
    "license": "proprietary",
    "require": {
        "php": "^7.4",
        "nyholm/psr7": "^1.1",
        "psr/http-client": "^1.0",
        "sensio/framework-extra-bundle": "^6.1",
        "symfony/asset": "^4.1",
        "symfony/flex": "^1.0",
        "symfony/framework-bundle": "^4.1",
        "symfony/messenger": "^4.1",
        "symfony/psr-http-message-bridge": "^1.0",
        "symfony/security-bundle": "^4.1",
        "symfony/yaml": "^4.1",
        "php-http/httplug": "^2.0",
        "php-http/guzzle6-adapter": "^2.0",
        "guzzlehttp/psr7": "^1.5"
    },

I have not set anything in services.yaml file.

2

There are 2 answers

1
Anjana Silva On

This is how you'd retrieve the request stack on Symfony 4.x version.

use Symfony\Component\HttpFoundation\RequestStack;

class HelloController 
{      

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

} 

The above was extracted from here:- https://symfony.com/doc/4.4/service_container/request.html

0
Joyce Babu On

The HttpFoundation request object to PSR7 ServerRequestInterface implementation conversion was performed by SensioFrameworkExtraBundle.

But the support was removed in v6

Either downgrade to v5.5 or switch to alternative.

The following bundle provides the removed feature and is based on the original implementation.

https://github.com/ajgarlag/psr-http-message-bundle