Silex + Doctrine ORM doesn't fire events when set to @MappedSuperclass

I am using Silex with Doctrine ORM, everything works fine, but I have a problem that I cannot figure out.

I have an Entity News in the Lpdq \ Model \ Entity namespace that extends another News class in the Lpdq \ Model namespace that contains some pre / post event methods and methods for doctrine.

My Essence News

<?php

namespace Lpdq\Model\Entity;

/**
 * News
 * 
 * @Table(name="news")
 * @Entity(repositoryClass="Lpdq\Model\Entity\Repository\News")
*/
class News extends Lpdq\Model\News{
 /*some properties/methods*/
}

      

My Superclass News

<?php

namespace Lpdq\Model;
/**
 * News
 * 
 * @MappedSuperclass
 * @HasLifecycleCallbacks
*/
class News{

   /**
    * @PrePersist
    */
    public function prePersist()
    {
        $this->setCreated(new \DateTime());
        $this->setUpdated(new \DateTime());
    }

    /**
     * @PreUpdate
     */
    public function preUpdate()
    {
        $this->setUpdated(new \DateTime());
    }

    /*...some methods...*/
}

      

In my controller I just instantiate my object and save / hide it

<?php

namespace Lpdq\Controller;

use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Lpdq\Model\Entity\News;

class NewsController {

    public function addAction( Request $request, Application $app) {
        $news = new News();
        $news->setTitle('test');
        /*...*/
        $app['orm.em']->persist($news);
        $app['orm.em']->flush();

        /*...*/
    }
}

      

My problem is that my prePersist / preUpdate methods are not called when I save my entity. (So ​​I get an error because my properties are created and updated to zero)

If I set my News entity to HasLifecycleCallbacks and apply the same prePersist / Update method, they fire.

While I'm here, I'm wondering if the way I extend my entities to put pre / post and other methods is good or bad practice?

+3


source to share


2 answers


If you have several objects that need the same set of methods, then the presence of base class news makes sense, if only one object extends class news, then this is overkill, and you can put the code in your entity class.

General pattern: if you have multiple entities and everyone has created and updated a field for them, then you must create a base class and all such objects must extend it.



To enable Lifecycle callbacks, the HasLifecycleCallbacks annotation is required. If lifecycle events are applicable to all objects that you propagate from the base class, then you must put the annotation in the base class, otherwise put it in separate classes.

0


source


You have an Lpdq\Model\Entity\News

extension Lpdq\Model\News

that is confusing at least. You are also only showing a partial implementation - make sure to setTitle()

actually update the tracked model properties for Doctrine to identify the instance as dirty. Otherwise, reset events will not be triggered.



0


source







All Articles