Reputation: 2936
I'm currently using an entity with a specific ID in a service. To make this work using dependency injection, I am injecting the entity repository and a specific ID. For example:
public function __construct($myRepo, $myId) {
$this->myEntity = $myRepo->find($myId);
}
Is there a way to directly inject this specific entity without passing in the repository? For example, the ideal method would be:
public function __construct($myEntity) {
$this->myEntity = $myEntity;
}
I can't figure out how to define the services that are needed to do this.
Upvotes: 0
Views: 85
Reputation: 48865
@Wouter makes a good point about services being stateless. However, you can use the DI factory capability to accomplish your goal:
specific_entity:
class: SomeEntity # Not used but you still need something here
factory_service: specific_entity_repository
factory_method: find
arguments:
- 42
This will call the find method on your repository with an argument of 42. The returned entity will then be injected. I'm assuming you already know how to setup a repository as a service.
Upvotes: 1
Reputation: 41934
Services should be stateless. Saving a user with a specific id in a service makes them statefull.
Instead of passing the entity in the constructor and saving it in a property, the entity should be passed to the method that is called. E.g. instead of a mailer with the to
address passed into the constructor, it should be passed to the mailer#mail()
method.
Upvotes: 4