Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

constructor injection in symfony

Tags:

php

symfony

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;

    }

}
like image 279
sina Avatar asked Oct 17 '22 21:10

sina


1 Answers

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 ;-)

like image 136
Strabek Avatar answered Oct 28 '22 23:10

Strabek