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.
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
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