1

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

melnikoved
  • 111
  • 1
  • 10
  • Are you sure `$this->getUser()` does what you think it does? You provide no code, so I can only assume that it retrieves an existing user rather than calling `new` therefore it is expected that `__construct()` is not triggered. Try `$user = new \Shop\UserBundle\Entity\User(); $user->getShop();` to see if it works... – dbrumann Apr 10 '13 at 19:09
  • yes. it's work's. But, if i use $this->getUser()->getShop() it doesn't work. But get_class($this->getUser()) - 'Shop\UserBundle\Entity\User' – melnikoved Apr 10 '13 at 20:11
  • As the answer below says, you have to add the property to the mapping, e.g. by adding annotations, and then updating the schema: `php app/console doctrine:schema:update --force`. Otherwise your property won't be saved and therefore will be null when you retrieve a previously persisted user. – dbrumann Apr 11 '13 at 16:49

2 Answers2

3

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;
    }
}
Alejandro Fiore
  • 1,117
  • 14
  • 18
1

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.

Community
  • 1
  • 1
l3l0
  • 3,363
  • 20
  • 19