Symfony2 - 在实体构造函数中设置默认值

hip*_*sis 7 entity default symfony

我可以设置一个简单的默认值,如字符串或布尔值,但我找不到如何为实体设置defualt.

在我的User.php实体中:

/**
* @ORM\ManyToOne(targetEntity="Acme\DemoBundle\Entity\Foo")
*/
protected $foo;
Run Code Online (Sandbox Code Playgroud)

在构造函数中,我需要为$ foo设置一个默认值:

public function __construct()
{
    parent::__construct();

    $this->foo = 1; // set id to 1
}
Run Code Online (Sandbox Code Playgroud)

期望一个Foo对象,它传递一个整数.

设置默认实体ID的正确方法是什么?

Raf*_*del 10

我认为你最好将它设置在一个PrePersist事件中.

User.php:

use Doctrine\ORM\Mapping as ORM;

/**
* ..
* @ORM\HasLifecycleCallbacks
*/
class User 
{
         /**
         * @ORM\PrePersist()
         */
        public function setInitialFoo()
        {
             //Setting initial $foo value   
        }

}
Run Code Online (Sandbox Code Playgroud)

但是设置关系值不是通过设置整数来执行的id,而是通过添加实例来执行Foo.这可以在事件监听器内完成,而不是实体的LifecycleCallback事件(因为你必须调用Foo实体的存储库).

首先,在捆绑services.yml文件中注册事件:

services:
    user.listener:
        class: Tsk\TestBundle\EventListener\FooSetter
        tags:
            - { name: doctrine.event_listener, event: prePersist }
Run Code Online (Sandbox Code Playgroud)

FooSetter班级:

namespace Tsk\TestBundle\EventListener\FooSetter;

use Doctrine\ORM\Event\LifecycleEventArgs;
use Tsk\TestBundle\Entity\User;

class FooSetter
{
    public function prePersist(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();
        $entityManager = $args->getEntityManager();

        if ($entity instanceof User) {
            $foo = $entityManager->getRepository("TskTestBundle:Foo")->find(1);
            $entity->addFoo($foo);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


And*_*son 5

在这个简单的例子中,我会远离听众,并将 传递EntityManager给一个实体。

一种更简洁的方法是将您需要的实体传递到新实体中:

class User
{

    public function __construct(YourEntity $entity)
    {
        parent::__construct();

        $this->setFoo($entity);
    }
Run Code Online (Sandbox Code Playgroud)

然后,当您在其他地方创建新实体时,您将需要在以下位置查找并传递正确的实体:

$foo = [find from entity manager]
new User($foo);
Run Code Online (Sandbox Code Playgroud)

- 额外的 -

如果您想更进一步,那么实体的创建可以在服务中:

$user = $this->get('UserCreation')->newUser();
Run Code Online (Sandbox Code Playgroud)

这可能是:

function newUser()
{
    $foo = [find from entity manager]
    new User($foo);
}
Run Code Online (Sandbox Code Playgroud)

这将是我的首选方式