Scu*_*Kay 6 service dependency-injection symfony
我正在编写一个Symfony 2.6应用程序,我在尝试将RequestStack注入服务时遇到了问题.我想要的是能够从我的服务中获取当前请求,但我得到以下异常:
ServiceNotFoundException: The service "host_service" has a dependency on a non-existent service "request_stack".
Run Code Online (Sandbox Code Playgroud)
我的服务 我的服务代码如下所示:
<?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
}
}
Run Code Online (Sandbox Code Playgroud)
Services.yml
我已经创建了一个这样的services.yml文件:
# MyBundle/Resources/config/services.yml
services:
host_service:
class: MyBundle\DependencyInjection\HostService
arguments: ["@request_stack"]
Run Code Online (Sandbox Code Playgroud)
延期
我还为我的包创建了一个扩展:
<?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');
}
}
Run Code Online (Sandbox Code Playgroud)
调节器
我使用该服务的方式是这样的:
$hostService = $this->get('host_service');
$something = $hostService->getSomething();
Run Code Online (Sandbox Code Playgroud)
也试过了
我也尝试使用这样的方法注入它:
protected $request;
public function setRequest(RequestStack $request)
{
$this->request = request;
}
Run Code Online (Sandbox Code Playgroud)
但这也没有用(同样的例外,是的,我也改变了Services.yml中的服务).
这个问题
根据Symfony.com 上的这篇文章,您不应该注入Request服务并使用RequestStack.我一直试图在文章正在做的同样的事情中做到这一点,但它仍然无法正常工作.
我忘记了什么吗?我是否以错误的方式使用这些服务(这是我的第一个服务)?我没有看到什么?为什么service_stack服务不存在?最重要的是:为什么这不起作用?
导致解决方案的信息
我使用的是Symfony 2.3,而不是Symfony 2.6.
使用 php app/console container:debug 或 debug:container for 2.6 检查服务是否存在,也许你使用了错误版本的 symfony
| 归档时间: |
|
| 查看次数: |
2474 次 |
| 最近记录: |