【问题标题】:Symfony 3 service dependencie [duplicate]Symfony 3服务依赖项[重复]
【发布时间】:2016-08-01 09:24:16
【问题描述】:

我尝试使用 symfony 3 创建服务。 我复制了在旧 Symfony2 版本上所做的现有服务文件。

services:
    agora.accessService:
        class: Agora\APIBundle\Services\AccessService
        scope: request
        arguments: ['@request', '@logger', '@doctrine.orm.default_entity_manager', '@session']

问题是我想将请求作为参数注入构造函数。它曾经在旧版本上工作,但现在我有这个错误:

The service "agora.accessservice" has a dependency on a non-existent service "request".

当然在我的服务类上我已经添加了use Symfony\Component\HttpFoundation\Request;

【问题讨论】:

  • 我应该再搜索一下。我找到了一个可行的解决方案,其中包括注入请求堆栈而不是请求。

标签: service dependencies symfony


【解决方案1】:

确实,因为Symfony 2.4 你必须注入request_stack 服务而不是请求服务

【讨论】:

    【解决方案2】:
    services:
        agora.accessService:
            class: Agora\APIBundle\Services\AccessService
            scope: request
            arguments: ['@request_stack', '@logger', '@doctrine.orm.default_entity_manager', '@session']
    

    我注入了请求堆栈而不是请求。效果很好。

    public function __construct(RequestStack $requestStack, ...)
    {
        $this->_request = $requestStack->getCurrentRequest();
    }
    

    【讨论】:

    • 小心。对于许多服务(尤其是标记服务),服务可能在请求可用之前就已创建。最好先存储请求堆栈,然后在实际需要时拉取请求。
    【解决方案3】:

    2017 和 Symfony 3.3+ 开始,这很简单:

    1。通过PSR-4 service autodiscovery注册自动装配服务

    # app/config/services.yml
    services:
        _defaults:
            autowire: true
    
        Agora\:
           resource: ../../src/Agora
    

    2。通过构造函数注入需要RequestStack 在服务中

    <?php
    
    namespace Agora\APIBundle\Services;
    
    class AccessService
    {
        /**
         * @var AnotherService 
         */
        private $requestStack;
    
        public function __construct(RequestStack $anotherService, LoggerInterface etc.)
        {
            $this->requestStack = $requestStack;
        }
    
        public function someMethod()
        {
            $request = $this->requestStack->getCurrentRequest();
            // ...
        }
    }
    

    您可以找到类似的答案,额外说明了如何在 Controller 中获取 Request,此处:https://stackoverflow.com/a/46867521/1348344

    【讨论】:

    • 好的,谢谢你的笔记。会做。我之前以更广泛的方式回答了类似的问题,但我被警告不要重复这些答案,这就是为什么我在这里保持简短。
    • 完成!在此编辑之后,我可以获得关于否决票的反馈吗?以防它们已经过时。
    • 不是我的反对票(我通常只标记这样的东西)。很多人开车不赞成仅链接的答案
    • 顺便说一句,回答问题然后投票结束并不被认为是犹太教。不是他们会禁止你的东西,只是皱眉
    • 我明白了。为什么你认为它是这样的顺序?我建议重复,但在几个小时没有回应后,我决定回答。而不是在不确定的时间内保留旧答案的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-23
    • 1970-01-01
    • 1970-01-01
    • 2018-04-06
    • 1970-01-01
    • 2013-03-05
    相关资源
    最近更新 更多