Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method return value as service parameter

Tags:

symfony

I'm trying to use a method-return-value as a DI-parameter. The concrete use-case is that I have a service that has the logic of calculating a users-country-code like:

$user->getCountryCode();

On the other hand I have many services that depend on the country like:

$foo = new Foo('UK');
$bar = new Bar('USA');

I know that I can inject the User service into Foo / Bar, but that creates an odd dependency as these services don't need a user they just need the country-code.

Is there a way for me to write a service-description along the lines of:

  my_services.foo:
    class: Foo
    arguments:
      - @user.getCountryCode

Edit: I'm using symfony 2.4 with yml configuration.

like image 651
gries Avatar asked May 07 '26 20:05

gries


1 Answers

Service factory method (compatible with all Symfony2 versions)

Service definitions:

# services.yml

FooFactory:
  class: Foo\FooBundle\Service\FooFactory
  arguments: [@user_country_code_calc_service]

FooService:
  class: Foo\FooBundle\Service\FooService
  factory_service: FooFactory
  factory_method: create

And your factory:

// FooFactory.php

class FooFactory
{
    private $countryCodeCalculator;

    public function __construct(UserCountryCodeCalculator $countryCodeCalculator)
    {
        $this->countryCodeCalculator = $countryCodeCalculator;
    }

    public function create()
    {
        $countryCode = $this->countryCodeCalculator->calculate(...);

        return new FooService($countryCode);
    }
}

Now when you inject @FooFactory in any of your services, Symfony will actually call FooFactory::create and inject that method's result into it.

like image 127
Igor Pantović Avatar answered May 10 '26 05:05

Igor Pantović