3

Im using Doctrine2 and I have a fair amount of model Objects.

All the objects inherit from a base class called BaseModel, and I need that every object call a method when its constructed. Since Doctrine doesnt call __construct, i cannot use that.

And from what I've seen, if I wanted to use the life cycle methods, I would have to modify all of my objects, they are over 50 of them...

Is there a way to define in one place a common life cycle method?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Hernan Rajchert
  • 896
  • 7
  • 19
  • can the BaseModel constructor call the method? – Nick Maroulis Oct 06 '11 at 00:09
  • 1
    @marabutt Doctrine's entity manager does not call class constructors on entity loading so that is not an option – Phil Oct 06 '11 at 00:30
  • possible duplicate of [Doctrine 2 LifecycleCallbacks with abstract base class are not called](http://stackoverflow.com/questions/7320425/doctrine-2-lifecyclecallbacks-with-abstract-base-class-are-not-called) – Phil Oct 06 '11 at 00:32

1 Answers1

2

Set your BaseModel to be a mapped superclass with the appropriate life cycle callbacks, eg

/** @MappedSuperclass @HasLifecycleCallbacks */
class BaseModel
{
    /** @PostLoad */
    public function doStuffOnPostLoad()
    {
        // do stuff
    }
}
Phil
  • 157,677
  • 23
  • 242
  • 245
  • The documentation says "This means that One-To-Many assocations are not possible on a mapped superclass at all.". And my classes do have one-to-many associations... Would you think it will work anyway?. Also note that I have non persisted clases extending this model too – Hernan Rajchert Oct 06 '11 at 01:12
  • You cannot have one-to-many relationships defined in the mapped superclass itself (`BaseModel`) however your entities may define them as usual AFAIK – Phil Oct 06 '11 at 01:17
  • Cool, in this case BaseModel is just an abstract class, nothing refers to it, but all the classes extends from it. So no problem with subclases of that referencing each other or having table iheritance? – Hernan Rajchert Oct 06 '11 at 01:21
  • @HernanRajchert Shouldn't be a problem – Phil Oct 06 '11 at 01:22