0

I am working on migrating an existing Symfony 2.8 project to Symfony 3.4 and would like to autowire / auto inject the value of the %kernel.environment% parameter into a controller action.

However binding the parameter to a argument name does not work:

// app/config/services.yml
services:
    _defaults:
        autowire: true
        autoconfigure: true
        public: false        

        bind:
            $kernelEnvironment: '%kernel.environment%'

        MyBundle\:
            resource: '../../src/MyBundle/*'
            exclude: '../../src/MyBundle/{Entity,Repository,Tests}'

        MyBundle\Controller\:
            resource: '../../src/MyBundle/Controller'
            tags: ['controller.service_arguments']


// src/MyBundle/SomeController.php
public function showPostAction($kernelEnvironment, $post_id) {
    ...
}

Uncaught PHP Exception RuntimeException: "Controller "MyBundle\Controller\SomeController::showPostAction()" requires that you provide a value for the "$kernelEnvironment" argument. Either the argument is nullable and no null value has been provided, no default value has been provided or because there is a non optional argument after this one."

Why does this not work?

I know that I could specify MyBundle\Controller\SomeController directly within in the services.yml and set the value of $kernelEnvironment in the arguments list. However this solution would mean that I would have to specify the argument for every controller that uses this parameter. This is is not what autorwire is good for. Binding the argument should work, shouldn't it?

Andrei Herford
  • 17,570
  • 19
  • 91
  • 225
  • I assume that the binding doesn't work for controllers, because they would like to handle them as route parameters. However try this in your controller to get this parameter: `$this->getParameter('%kernel.environment%')` – Fabian Schmick Jan 14 '19 at 12:40
  • 1
    For 3.4 you cannot use bind for controller actions, only constructor arguments. Bind works fine in 4.x. Just one of those things. A somewhat verbose discussion (and example) can be found [here](https://stackoverflow.com/questions/54009230/read-from-parameters-in-symfony-3-4-getparameter-null/54024701#54024701). – Cerad Jan 14 '19 at 13:46
  • @Cerad thanks for the hint. This seems to be the solution. However the limitations of bindings to constructors seems to be only true for parameters. Other bindings work well (e.g. $translator: '@translator.default'). If you add this info as answer I would accept it. – Andrei Herford Jan 14 '19 at 14:05
  • 1
    Yep. Only for parameters for some reason. Services seem to work just fine. Go figure. I kind of think this is basically a duplicate question. Feel free to up vote the linked answer if you want. – Cerad Jan 14 '19 at 14:10

0 Answers0