簡體   English   中英

Symfony2 - 在實體構造函數中設置默認值

[英]Symfony2 - Set default value in entity constructor

我可以設置一個簡單的默認值,如字符串或布爾值,但我找不到如何為實體設置defualt。

在我的User.php實體中:

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

在構造函數中,我需要為$ foo設置一個默認值:

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

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

期望一個Foo對象,它傳遞一個整數。

設置默認實體ID的正確方法是什么?

我認為你最好把它放在PrePersist活動中。

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實體的存儲庫)。

首先,在bundle services.yml文件中注冊事件:

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

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

在這個簡單的例子中,我會遠離監聽器,並且還將EntityManager傳遞給實體。

更簡潔的方法是將您需要的實體傳遞到新實體:

class User
{

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

        $this->setFoo($entity);
    }

然后在您創建新實體的其他地方,您需要找到並傳遞正確的實體:

$foo = [find from entity manager]
new User($foo);

- 額外 -

如果您想更進一步,那么實體的創建可以在服務中:

$user = $this->get('UserCreation')->newUser();

這可能是:

function newUser()
{
    $foo = [find from entity manager]
    new User($foo);
}

這將是我的首選方式

你不能只用'Foo'傳遞關系的id。 您需要首先檢索Foo實體,然后設置foo屬性。 為此,您需要一個Doctrine Entity Manager實例。 但是,你讓你的實體依賴於EntityManager,這是你不想要的。

例:

// .../User.php

public function __construct(EntityManager $em) {
    $this->em = $em;

    $this->foo = $this->em->getRepository('Foo')->find(1);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM