2

In symfony you have two ways of injecting something:

  1. Using the services.yml file
  2. Using the @required annotation

I am trying to move away from services.yml.
I can easily inject other services using the @required like this:

class SomeClass
{
    private LoggerInterface $logger;

    /** @required */
    public function setLogger(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }
}

Is there a way to inject a parameter using this method?
Currently I am using this hacky approach, but I was hoping for something more strait forward than injecting the entire container.

class SomeClass
{
    private array $configuration;

    /** @required */
    public function setConfiguration(ContainerInterface $container)
    {
        $this->configuration = $container->getParameter('my_bundle.config');
    }
}
HubertNNN
  • 1,727
  • 1
  • 14
  • 29
  • What version of Symfony do you use? Answers may be different if the project use [autowiring](https://symfony.com/doc/5.4/service_container/autowiring.html#an-autowiring-example), does it?. – A.L Jul 12 '23 at 13:47
  • Does this answer your question? [How to access an application parameters from a service?](https://stackoverflow.com/questions/11209529/how-to-access-an-application-parameters-from-a-service) How did you define `my_bundle.config`? – A.L Jul 12 '23 at 14:23
  • I use `Symfony 4.4`. The linked question does not answer mine, since all answers there either use `services.yml` or the workaround that I mentioned in my question, and I am looking for a solution that uses `@required` annotation. – HubertNNN Jul 13 '23 at 08:33
  • 1
    How did you define my_bundle.config? [This answer](https://stackoverflow.com/a/53172352/2257664) shows how to inject the parameter bag instead of the container. To my knowledge, you'll have to use `bind:`, pass the parameter bag or declare parameters explicitely, otherwise Symfony can't guess what is the expected value to pass. – A.L Jul 13 '23 at 08:46
  • ParameterBagInterface, as A.L suggests. Trying to "move away from services.yml" is bit weak as a reason, tbh. if you're concerned with writing entries for each and every service for the same paramters, the `_defaults` approach is really the way to go in symfony 4, as shown in the link from A.L. The ParameterBagInterface is the clean alternative. I would also use any of those approaches in symfony 5+, tbh. – Jakumi Jul 14 '23 at 05:03

0 Answers0