简体   繁体   中英

Symfony 2 - FOSUserBundle - Create and Persist another entity inside the constructor of User class

I'm making a website where users can create albums.
I would like to create a default album per user.

I would like to create an Album entity and to persist it in the constructor of my User class.

Is it possible ? I just know that the entityManager is not accessible from an Entity... That's why it's a problem for me.

Even though this technically IS possible I would strongly recommend you not to do this.

To answer your question, it is possible and it would be done like this:

class User extends FOSUser
{
    /**
     * @ORM\OneToMany(targetEntity="Album", cascade={"persist"})
     */
    private $albums;

    public function __construct()
    {
        $this->albums = new ArrayCollection();
        $this->addAlbum(new Album());
    }

    public function addAlbum(Album $album)
    {
        $this->albums[] = $album;
    }

    public function getAlbums()
    {
        return $this->albums:
    }
}

With setup like this whenever you create a new user and save it, a related album will be created together with it. I have to repeat, even though it's possible, don't do it like this .

Good solutions

There are few strategies that can be used to achieve what you want.

FOSUserBundle master

If you're not using 1.3.x version of FOSUserBundle but master, you can see that RegistrationController fires a few events. The one you're interested in is FOSUserEvents::REGISTRATION_INITIALIZE . You should create an event listener and add album to user in your listener.

FOSUserBundle 1.3.x

If you're using one of older versions, these events don't exist unfortunately and you can do it two ways.

  1. Extend FOSUserBundle UserManager and override createUser method . You can add your album adding logic there. I would prefer this approach.
  2. Override FOSUserBundle RegistrationController::registerAction. It can be viable option sometimes but in your case I think option 1 is better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM