FOSUserBundle:从FormHandler中获取存储库

时间:2012-04-02 08:34:39

标签: php symfony fosuserbundle

我需要在保存之前为新用户设置默认值。 问题是我找不到从FormHandler内部通过其存储库获取对象的方法。

<?php
namespace Acme\UserBundle\Form\Handler;

use FOS\UserBundle\Form\Handler\RegistrationFormHandler as BaseHandler;
use FOS\UserBundle\Model\UserInterface;

class RegistrationFormHandler extends BaseHandler
{

    protected function onSuccess(UserInterface $user, $confirmation)
    {
        $repository = $this->container->get('doctrine')->getEntityManager()->getRepository('AcmeUserBundle:Photo');
        if($user->isMale()){
            $photo = $repository->getDefaultForMale();
            $user->setPhoto($photo);
        }
        else {
            $photo = $repository->getDefaultForFemale();
            $user->setPhoto($photo);
        }

        parent::onSuccess($user, $confirmation);
    }
}

问题来自以下几行:

$repository = $this->container->get('doctrine')->getEntityManager()->getRepository('AcmeUserBundle:Photo');

...我找不到从这个FormHandler获取此存储库或实体管理器的方法。

非常感谢您的帮助! 甲

2 个答案:

答案 0 :(得分:4)

您必须定义一个引用扩展处理程序类的服务,并将其指向app/config.yml。 e.g

班级,

//namespace definitions
class MyHandler extends RegistrationFormHandler{

    private $container;

    public function __construct(Form $form, Request $request, UserManagerInterface $userManager, MailerInterface $mailer, ContainerInterface $container)
    {
        parent::__construct($form, $request, $userManager, $mailer);
        $this->container = $container;
    }

    protected function onSuccess(UserInterface $user, $confirmation)
    {
        $repository = $this->container->get('doctrine')->getEntityManager()->getRepository('AcmeUserBundle:Photo');

        // your code

    }

服务,

 my.registration.form.handler:
    scope: request
    class: FQCN\Of\MyHandler
    arguments: [@fos_user.registration.form, @request, @fos_user.user_manager, @fos_user.mailer, @service_container]

最后在app/config.yml

fos_user:
    #....
    registration:
      #...
      form:
        handler: my.registration.form.handler

答案 1 :(得分:-1)

FOS有自己的UserManager。尝试使用它。