简体   繁体   中英

Inject specific Doctrine entity in Symfony2 service

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.

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. Eg instead of a mailer with the to address passed into the constructor, it should be passed to the mailer#mail() method.

@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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM