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;
}
}
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 ;-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With