Reputation: 1427
There is already plenty of documentation on the internet about injecting a service into another service like this: http://symfony.com/doc/current/components/dependency_injection/introduction.html
However, I already have a service called ObjectCache
which is configured in symfony's services.yml like this:
object_cache:
class: App\Bundle\ApiBundle\Service\ObjectCache
This service currently has two methods for getting and setting a User object. For example:
$user = new User(); // assume entity from database
$this->get('object_cache')->setUser($user);
// ...
$this->get('object_cache')->getUser(); // instance of $user
I want to create a new service which always depends on a user, so makes sense to inject the user at service creation:
class SomeService {
public function __construct(User $user)
{
}
}
How would I configure services.yml such that the User is injected into my new service?
object_cache:
class: App\Bundle\ApiBundle\Service\ObjectCache
some_service:
class: App\Bundle\ApiBundle\Service\SomeService
arguments: [@object_cache->getUser()????]
This didn't work, and symfony yaml documentation is sketchy to say the least.
Am I basically forced into creating a User-only flavour of the ObjectCache and injecting that into SomeService OR expecting SomeService to receive an ObjectCache and call getUser once in the constructor?
Upvotes: 2
Views: 1257
Reputation: 1427
Credit to qooplmao for their comment in helping me find the answer as this is exactly what I was looking for. I thought I'd answer my own question for the benefit of others as I now have this working, plus some corrections to the syntax in the comment.
What I should have been looking for was Symfony's Expression Language which allows precisely the granularity of control I was looking for.
The resulting configuration now looks like this:
object_cache:
class: App\Bundle\ApiBundle\Service\ObjectCache
some_service:
class: App\Bundle\ApiBundle\Service\SomeService
arguments: [@=service('object_cache').getUser()]
For more information on the Expression Syntax, here is some detailed documentation: http://symfony.com/doc/2.7/components/expression_language/syntax.html
(If only Symfony docs had the courtesy to provide links to such crucial information on pages that make reference to it!)
Upvotes: 2