FOSUserBundle: Get an EntityManager instance overriding the form handler

I am starting with Symfony2 and I am trying to override FOS \ UserBundle \ Form \ Handler \ RegistrationFormHandler from 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 thing is, I need an instance of Doctrine Entity Manager, but I don’t know where / how to get it in this case!

Any idea?

Thanks in advance!

+1
source share
1 answer
  • You should not use EntityManager directly in most cases. Instead, use the appropriate manager / vendor service.

    In the case of using the FOSUserBundle service, the UserManagerInterface is such a manager. It is accessible through the fos_user.user_manager key in the service container (which is the alias of fos_user.user_manager.default ). Of course, the registration form handler uses this service , it is available through userManager .

  • You should not treat your domain model (Doctrine ia objects) as if it were an exact representation of the database model. This means that you must assign objects to other objects (not their identifiers).

    Doctrine is capable of handling nested objects inside your objects ( UserDetails and User objects have a direct relationship). In the end, you need to configure the cascade options for the User object.

  • Finally, UserDetails seems to be a required dependency for each User . Therefore, you must override UserManagerInterface::createUser() not a form handler - you still do not have any user information.

    • Create your own implementation of UserManagerInterface :

       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 serial inside the 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 
+2
source

Source: https://habr.com/ru/post/951658/


All Articles