7

i want to use Request class in my constructor and this is the error it gives to me while i want to run server:

Cannot autowire service "AppBundle\Controller\DetectServiceDetailController": argument "$request" of method "__construct()" references class "Symfony\Component\HttpFoundation\Request" but no such service exists. It cannot be auto-registered because it is from a different root namespace.

my code:

<?php

namespace AppBundle\Controller;

use Symfony\Component\HttpFoundation\Request;

class DetectServiceDetailController
{
    public $request;

    public function __construct(Request $request)
    {
        $this->request = $request;
        $serviceType = $this->request->query->get('type');
        return $serviceType;

    }

}
12
  • symfony 3 or 4? Commented Mar 10, 2018 at 13:42
  • 7
    Anyway you should inject the RequestStack class instead of Request. Commented Mar 10, 2018 at 13:42
  • @AlexKarshin 3.4 Commented Mar 10, 2018 at 13:46
  • 1
    @sina read How to Retrieve the Request from the Service Container and API Reference Commented Mar 10, 2018 at 13:53
  • 1
    @gp_sflover Don't get offended :) Yes, best practice is to inject only what you need and even better when you need it, that's why in our team we inject Request right into controller methods. Commented Mar 10, 2018 at 14:13

1 Answer 1

7

As per gp_sflover's suggestion here is a piece of code I use in Symfony 3.4:

<?php

namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RequestStack;

class BaseController extends Controller
{
    protected $request;

    /**
     * @param Symfony\Bundle\FrameworkBundle\Controller\Controller
     */
    public function __construct(RequestStack $requestStack)
    {
        $this->request = $requestStack->getCurrentRequest();
    }

    ...

In my case BaseController extends Controller so I don't need to update services.yml, but if this is stand alone service then you need to add it to services.yml e.g.

services:
    ...
    service_name:
        class: AppBundle\Service\ServiceName
        arguments:
            - '@request_stack'
        public: true

Just adding it for less experienced devs ;-)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.