【问题标题】:Extend function with Doctrine ORM Annotation使用 Doctrine ORM 注释扩展功能
【发布时间】:2013-04-08 13:51:01
【问题描述】:

我遇到了以下情况:扩展 DataObject 类的(Doctrine Entity)ContentCategory。 DataObject 类有以下函数,onPrePersist:

/**
*  @ORM\HasLifecycleCallbacks
*/
class DataObject implements InputFilterAwareInterface
{
 ...
 /** @ORM\PrePersist */
 public function onPrePersist()
 {
     //using Doctrine DateTime here
     $this->creation_date = new \DateTime('now');
 }

ContentCategory 类也需要这个函数。当我将此函数放在 ContentCategory 类中时,它工作得很好。有没有办法让 ContentCategory 类可以使用相同的函数 onPrePersist() 而无需在类本身中定义它?

* @ORM\HasLifecycleCallbacks()
*/
class ContentCategory extends DataObject implements InputFilterAwareInterface
{
 ...
}

为对象提供 onPrePersist 函数的原因是,在创建此对象或任何其他扩展 DataObject 类的对象/实体时设置一个 DateTime。

----

我目前向 ContentCategory 添加了一个构造方法,如下所示:

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

这样,Doctrine 在创建新实体时执行 onPersist 函数。另一种情况是使用 Doctrine 更新实体时。我想设置一个 Modified_date。在这种情况下,DataObject 类中就会有这样的函数。

/**
*  @ORM\HasLifecycleCallbacks
*/
class DataObject implements InputFilterAwareInterface
{
 ...
/**
 * @ORM\PreUpdate
 */
public function onUpdate()
{
    $this->last_modified_date = new \DateTime('now');
}

已添加的 Doctrine ORM 注释 (PreUpdate) 将确保函数(如上)将在对象的更新语句上执行。问题是,如何在扩展 DataObject 的对象中调用这些函数

【问题讨论】:

    标签: zend-framework orm doctrine-orm doctrine


    【解决方案1】:
    /**
     * @ORM\MappedSuperclass
     * @ORM\HasLifecycleCallbacks
     */
    class TestimonialSuperclass
    {
        /**
         * @ORM\PreFlush
         */
        public function onPreFlush ()
        {
            echo 123;
        }
    }
    
    
    /**
     * @ORM\Entity
     * @ORM\Table(name="testimonials")
     * @ORM\HasLifecycleCallbacks
     */
    class Testimonial extends TestimonialSuperclass
    {
       ...
    }
    

    【讨论】:

    • 谢谢,我不知道 Doctrine ORM Annotation: MappedSuperclass。使用此注释,它不会为超级(父)类创建实体。非常感谢,让我大开眼界!
    猜你喜欢
    • 2020-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-12
    • 2018-11-24
    • 1970-01-01
    • 2015-10-17
    相关资源
    最近更新 更多