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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With