Symfony2-在实体构造函数中设置默认值 [英] Symfony2 - Set default value in entity constructor

查看:221
本文介绍了Symfony2-在实体构造函数中设置默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I can set a simple default value such as a string or boolean, but I can't find how to set the defualt for an entity.

在我的用户中.php实体:

In my User.php Entity:

/**
* @ORM\ManyToOne(targetEntity="Acme\DemoBundle\Entity\Foo")
*/
protected $foo;

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

In the constructor I need to set a default for $foo:

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

    $this->foo = 1; // set id to 1
}

应该有一个Foo对象,它会传递一个整数

A Foo object is expected and this passes an integer.

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

What is the proper way to set a default entity id?

推荐答案

我认为您最好将其设置在 PrePersist 事件中。

I think you're better to set it inside a PrePersist event.

User.php

use Doctrine\ORM\Mapping as ORM;

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

}

但是设置关联值并不是通过设置整数 id ,而是通过添加 Foo 的实例来实现的。这可以比实体的 LifecycleCallback 事件更好地在事件侦听器中完成(因为您必须调用 Foo 实体的存储库)。

But setting a relation value is not carried out by setting an integer id, rather it's carried out by adding an instance of Foo. And this can be done inside an event listener better than the entity's LifecycleCallback events (Because you'll have to call Foo entity's repository).

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

First, Register the event in your bundle services.yml file:

services:
    user.listener:
        class: Tsk\TestBundle\EventListener\FooSetter
        tags:
            - { name: doctrine.event_listener, event: prePersist }

c $ c> FooSetter 类:

And the FooSetter class:

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);
        }
    }
}

这篇关于Symfony2-在实体构造函数中设置默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆