Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

php - Doctrine 2 LifecycleCallbacks with abstract base class are not called

I have this situation:

Abstract Class:

abstract class AbstractBase
{
    /**
     * @ORMId
     * @ORMGeneratedValue
     * @ORMColumn(type="integer")
     * @var integer
     */
    protected $id;

    /**
     * @ORMColumn(type="datetime", name="updated_at")
     * @var DateTime $updatedAt
     */
    protected $updatedAt;

    /**
     * @ORMPreUpdate
     */
    public function setUpdatedAt()
    {
        die('THIS POINT IS NEVER REACHED');
        $this->updatedAt = new DateTime();
    }
}

Concrete Class:

/**
 * @ORMEntity(repositoryClass="EntityRepositoryUserRepository")
 * @ORMTable(name="users")
 * @ORMHasLifecycleCallbacks
 */
class User extends AbstractBase
{
    // some fields, relations and setters/getters defined here, these all work as expected.
}

Then i call it in my controller like this:

$user = $this->em->find('EntityUser', 1);
// i call some setters here like $user->setName('asd');
$this->em->flush();
die('end');

Everything works as expected, so the id field from the abstract class gets created for the User entity, i can access it etc. The problem is, that the line "die('THIS POINT IS NEVER REACHED')" is never reached. (Note the @ORMPreUpdate) This means that lifecycleCallbacks are not called on inherited objects. Is this a bug, or is there a reason for this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your abstract base class has to be anotated as Mapped Superclasses and include the HasLifecycleCallbacks-Annotation.

Further Information: Inheritance Mapping in the Doctrine Documentation.

/**
 * @ORMMappedSuperclass
 * @ORMHasLifecycleCallbacks
 */
abstract class AbstractBase
{
    [...]

    /**
     * @ORMPreUpdate
     */
    public function setUpdatedAt()
    {
        $this->updatedAt = new DateTime();
    }
}

/**
 * @ORMEntity(repositoryClass="EntityRepositoryUserRepository")
 * @ORMTable(name="users")
 */
class User extends AbstractBase
{
    // some fields, relations and setters/getters defined here, these all work as expected.
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...