I am writing a Symfony 2.6 application and I've encountered a problem when trying to inject the RequestStack into a service. What I want is to be able to get the current request from within my service, but I'm getting the following exception:
ServiceNotFoundException: The service "host_service" has a dependency on a non-existent service "request_stack".
My service My code for the service looks like this:
<?php
namespace MyBundle\DependencyInjection;
use Symfony\Component\HttpFoundation\RequestStack;
class HostService
{
protected $request;
public function __construct(RequestStack $requestStack)
{
$this->requestStack = $requestStack;
}
public function getSomething()
{
$request = $this->requestStack->getCurrentRequest();
// Do stuff with the request stack
// return something
}
}
Services.yml
I've created a services.yml file like this:
# MyBundle/Resources/config/services.yml
services:
host_service:
class: MyBundle\DependencyInjection\HostService
arguments: ["@request_stack"]
Extension
I have also created an extension for my bundle:
<?php
namespace MyBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
class MyExtension extends Extension
{
public function load(array $configs, ContainerBuilder $container)
{
$loader = new YamlFileLoader(
$container,
new FileLocator(__DIR__.'/../Resources/config')
);
$loader->load('services.yml');
}
}
Controller
The way I'm using the service is like this:
$hostService = $this->get('host_service');
$something = $hostService->getSomething();
Also tried
I also tried injecting it using a method like this:
protected $request;
public function setRequest(RequestStack $request)
{
$this->request = request;
}
But this also did not work (same exception, and yeah I also changed the service in Services.yml).
The question
According to this article on Symfony.com, you should not inject the Request service and use the RequestStack instead. I've been trying to do this in the same matter the article is doing it, but it still won't work.
Am I forgetting something? Am I using the services in the wrong way altogether (this is my first service)? Am I not seeing something? Why does the service request_stack not exist? Most of all: why is this not working?
The information that led to a solution
I am using Symfony 2.3, not Symfony 2.6.
Since 2017 and Symfony 3.3+ this is now very simple.
1. Register services with autowiring via PSR-4 service autodiscovery
2. Require
RequestStack
in service via Constructor Injection3. Or in Controllers, require
Request
as action method argumentNothing more is needed.
Happy coding!
Use php app/console container:debug or debug:container for 2.6 to check if the service exists , and maybe you are using the wrong version of symfony