melnikoved
melnikoved

Reputation: 111

Why __construct method don't work in User Entity in FOSUserBundle?

I am using the FOSUserBundle.

This is the User Entity:

namespace Shop\UserBundle\Entity;

use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

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

    protected $shop;

    public function __construct()
    {
        $this->shop = 'shop';
        parent::__construct();
    }

    public function getShop()
    {
        return $this->shop;
    }
}

When I call getShop in the controller:

$user = $this->getUser()->getShop()

A result is null
Why does not __construct work in User class? I expected to have 'shop' string as default

Upvotes: 1

Views: 3343

Answers (2)

Alejandro Fiore
Alejandro Fiore

Reputation: 1157

You can put a callback to iniatilize your User. Just two annotations @ORM\HasLifecycleCallbacks for the entity and @ORM\PostLoad for the method. For example:

namespace Shop\UserBundle\Entity;
use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
 * @ORM\Entity
 * @ORM\Table(name="fos_user")
 * @ORM\HasLifecycleCallbacks
 */
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    protected $shop;

    /**
     * @ORM\PostLoad
     */
    public function init()
    {
        $this->shop = 'shop';
        parent::init();
    }

    public function getShop()
    {
        return $this->shop;
    }
}

Upvotes: 3

l3l0
l3l0

Reputation: 3393

Basically __construct in doctrine entity is called directly in end user code. Doctrine does not use construct when fetch entities from database - please check that question for more details. You can persist this in database by adding mapping if you want.

Upvotes: 1

Related Questions