Symfony2 - FOSUserBundle在注册后设置用户实体字段

时间:2014-07-15 23:49:09

标签: php symfony fosuserbundle symfony-2.5

我有一个带有firstname,lastname和url属性的用户实体,扩展了FOSUserBundle用户。我想在url属性中将fistname和lastname的值存储为一个strig。

有些人建议我应该使用听众和服务,所以我做了:

该事件似乎在注册后有效,但我无法找到更改用户网址的方法......

servises.yml

services:
   kernel.listener.RegistrationListener:
      class: Apana\Bundle\MainBundle\EventListener\RegistrationListener
      tags:
          - { name: kernel.event_listener, event: fos_user.registration.completed, method: onUserRegistration }

在RegistrationListener.php中:

    <?php

namespace Apana\Bundle\MainBundle\EventListener;

use Apana\Bundle\MainBundle\Entity\User;
use Symfony\Component\Security\Core\SecurityContext;
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\UserEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\HttpKernel;

class RegistrationListener
{

    public function onUserRegistration()
    {
        $user = new User();

        $ap= = $user->getFirstname();
        echo($ap);exit();

    }

}

3 个答案:

答案 0 :(得分:1)

为什么你不使用UserManager而不是听众?我会用自己的方式覆盖FOSUser寄存器并执行以下操作:

$userManager = $this->container->get('fos_user.user_manager');
$user = $userManager->createUser();

$user->setUrl("any data");

至少对我来说,它更简单,更简单

答案 1 :(得分:1)

如果我理解正确,你想做的是一个带有firstname和lastname字段的slug 用作slug的名字和姓氏也必须被消毒以替换重音字符,空格等。

要自动执行所有操作,您可以使用Doctrine Extension,特别是Sluggable:https://github.com/Atlantic18/DoctrineExtensions/blob/master/doc/sluggable.md

这是一个使用注释的例子:

<?php
// src/Acme/UserBundle/Entity/User.php

namespace Acme\UserBundle\Entity;

use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * @ORM\Entity
 * @ORM\Table(name="fos_user")
 */
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(length=64, unique=false)
     */
    private firstname;

    /**
     * @ORM\Column(length=64, unique=false)
     */
    private lastname;

    /**
     * @Gedmo\Slug(fields={"firstname", "lastname"}, separator="-")
     * @ORM\Column(length=128, unique=true)
     */
    private $slug;

    public function __construct()
    {
        parent::__construct();
        // your own logic
    }

    //... setter and getter...
}

答案 2 :(得分:0)

好的,我用eventlistener和FOSUserBundle UserEvent解决了我的问题

 <?php

namespace Apana\Bundle\MainBundle\EventListener;

use FOS\UserBundle\Event\UserEvent;

class RegistrationListener
{

    public function onUserRegistration(UserEvent $event)
    {
        $user = $event->getUser();
        $url =  strtolower($user->getFirstname().".".$user->getLastname());
        $user->setUrl($url);
    }

}