Tagged: doctrine 2 injection
2014/09/19 at 3:25 pm #591
Thanks for a good book! In the chapter Better security\User Entity (in my book it is on page 141) you define ‘initializers’ => array (‘User\Service\Initializer\Password’) under both the service manager key and the doctrine key. Why are both necessary? I realize that you stated earlier that when Doctrine creates entity instances it does not inject their dependencies. Does that mean that $this->serviceLocator->get(‘user-entity’) will not inject its dependencies? If so, why did you define the initializer under the service manager key altogether? It seems that the only one that is working for me is the service manager initializer while the other one does not seem to work. Please can you clarify this for me.
Thank you.2014/09/23 at 4:48 pm #601
Thanks for the kind words.
> Why are both necessary
For dependency injection in Doctrine 2 entities that are created directly using the Doctrine 2 entity manager.
If we get an entity always from our service manager and we have initializers there, then that is not needed.
But when we use Doctrine 2 from the entity manager we may decide to get an entity instance directly.
$entityManager = $serviceMananager->get('entity-manager'); $objectFromDoctrine = $entityManager->find('The\Class\That\WeNeed', 123);
In that case our service manager initializer will not be called at all. And for this we need to add an initializer for the Doctrine 2 IF we want to have dependency injection.
In Doctrine 2 if you want to get an entity it creates an object BUT it does not run the constructor of the class that is responsible for it. Doctrine 2 never instantiates the constructor of your entities. “we store a prototype class instance that is unserialized from a hand crafted serialized string where the class name is concatenated into the string. The result when we unserialize the string is an instance of the class which is stored as a prototype and cloned everytime we need a new instance during hydration.” ( http://www.doctrine-project.org/2010/03/21/doctrine-2-give-me-my-constructor-back.html). Which means that if we want every new entity to have something injected we should do it either in the constructor or ourselves. And in Doctrine 2 that is possible if we listen to the post_load event and inject our dependencies. For that we need Doctrine 2 initializers.
You must be logged in to reply to this topic.