Non-existent service “request_stack”

后端 未结 2 1380
失恋的感觉
失恋的感觉 2021-01-18 05:09

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 re

相关标签:
2条回答
  • 2021-01-18 05:51

    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

    0 讨论(0)
  • 2021-01-18 05:55

    Since 2017 and Symfony 3.3+ this is now very simple.

    1. Register services with autowiring via PSR-4 service autodiscovery

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

    2. Require RequestStack in service via Constructor Injection

    <?php
    
    namespace App;
    
    use Symfony\Component\HttpFoundation\RequestStack;
    
    final class SomeService
    {
        /**
         * @var AnotherService 
         */
        private $requestStack;
    
        public function __construct(RequestStack $anotherService)
        {
            $this->requestStack = $requestStack;
        }
    
        public function someMethod()
        {
            $request = $this->requestStack->getCurrentRequest();
            // ...
        }
    }
    

    3. Or in Controllers, require Request as action method argument

    <?php
    
    namespace App;
    
    use Symfony\Component\HttpFoundation\Request;
    
    final class SomeController
    {
        public function someAction(Request $request)
        {
            $request->...;
        }
    }
    

    Nothing more is needed.

    Happy coding!

    0 讨论(0)
提交回复
热议问题