问题
I am starting with Symfony2 and I am trying to override FOS\UserBundle\Form\Handler\RegistrationFormHandler of FOSUserBundle.
My code is:
<?php
namespace Testing\CoreBundle\Form\Handler;
use FOS\UserBundle\Model\UserInterface;
use FOS\UserBundle\Form\Handler\RegistrationFormHandler as BaseHandler;
use Testing\CoreBundle\Entity\User as UserDetails;
class RegistrationFormHandler extends BaseHandler
{
protected function onSuccess(UserInterface $user, $confirmation)
{
// I need an instance of Entity Manager but I don't know where get it!
$em = $this->container->get('doctrine')->getEntityManager();
// or something like: $em = $this->getDoctrine()->getEntityManager
$userDetails = new UserDetails;
$em->persist($userDetails);
$user->setId($userDetails->getId());
parent::onSuccess($user, $confirmation);
}
}
So, the point is that I need an instance of Doctrine's Entity Manager but I don't know where/how get it in this case!
Any idea?
Thanks in advance!
回答1:
You should not use
EntityManager
directly in most of the cases. Use a proper manager/provider service instead.In case of FOSUserBundle service implementing UserManagerInterface is such a manager. It is accessible through
fos_user.user_manager
key in the service container (which is an allias to fos_user.user_manager.default). Of course registration form handler uses that service, it is accessible through userManager property.You should not treat your domain-model (i.a. Doctrine's entities) as if it was exact representation of the database-model. This means, that you should assign objects to other objects (not their ids).
Doctrine is capable of handling nested objects within your entities (
UserDetails
andUser
objects have a direct relationship). Eventually you will have to configure cascade options forUser
entity.Finally,
UserDetails
seems to be a mandatory dependency for eachUser
. Therefore you should overrideUserManagerInterface::createUser()
not the form handler - you are not dealing with user's details there anyway.Create your own
UserManagerInterface
implementation:class MyUserManager extends \FOS\UserBundle\Entity\UserManager { /** * {@inheritdoc} */ public function createUser() { $user = parent::createUser(); $user->setUserDetails(new UserDetails()); // some optional code required for a proper // initialization of User/UserDetails object // that might require access to other objects // not available inside the entity return $user; } }
Register your own manager as a serive inside DIC:
<service id="my_project.user_manager" class="\MyProject\UserManager" parent="fos_user.user_manager.default" />
Configure FOSUserBundle to use your own implementation:
# /app/config/config.yml fos_user: ... service: user_manager: my_project.user_manager
来源:https://stackoverflow.com/questions/12574665/fosuserbundle-get-entitymanager-instance-overriding-form-handler