I have a dilemma on how to implement states for objects.
Let’s say we have this:
class User {
private $_active;// 1 or 0
private $_deleted;// 1 or 0
...
}
These properties – as I see it – imply a state on User object.
What I would like to do is to define some events like afterActivate() or afterDelete() so I can chain my routines. I.e. after activation update some counters, after deletion also update some counters…
So I’m considering two approaches at the moment – first one is to create classes Activable and Deletable ( don’t mind the naming ) and then make User inherit those classes through a hierarchy of inheritance.
class Activable {
protected afterActivate(){};
}
class Deletable {
protected afterDelete(){};
}
class Activable extends Deletable {}
class User extends Activable{}
There are two problems that I see with this approach – first one is that class Activable now has implied Deletable state which is wrong and second problem is – if I have more states – 5-6 states the inheritance hierarchy may become quite complex. ( because User will extend the model class which will extend something else etc…)
The second approach is to use traits in PHP and use them to achieve this.
So I would have something like
class User{
use Activable, Deletable;
}
What approach would be better – maybe some 3rd approach?
Am I going in the right direction here?
Thanx.
Usually you would use
Marker Interfaces for this sort of thing.I suppose this is some kind of ORM we’re talking about? Than I also assume there is some kind of object handling the persistence of your entities. Let that object check that
$entity instanceof Deletableand act upon that.