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!
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 throughfos_user.user_manager
key in the service container (which is an allias tofos_user.user_manager.default
). Of course registration form handler uses that service, it is accessible throughuserManager
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:Register your own manager as a serive inside DIC:
Configure FOSUserBundle to use your own implementation: