I am searching for a architectural solution in instantiating different child classes based on an object type or extending Base class with the methods of child classes.
To give an example:
There is a base class User and several child classes Partner, Client, Moderator which have specific methods an their own constructors.
When I am calling
$user = new User($userid);
I want User class
class User
{
public function __construct($userid) {
self::initDB();
if ($this->isPartner()) {
//extend this class with the methods of "Partner" child class and run "Partner" class constructor
}
if ($this->isClient()) {
//extend this class with the methods of "Client" child class and run "Client" class constructor
}
if ($this->isModerator()) {
//extend this class with the methods of "Moderator" child class and run "Moderator" class constructor
}
}
}
To return me an object with all of the methods depending on what roles does user have.
I know my logic is broken somewhere and the example I provided is wrong. But the only solution I see now is to build one giant class that has all of the methods for all of the roles – which looks like a mess.
First of all, your database logic should be totally separate from your domain objects (User, etc). Otherwise you are violating the single responsibility principle (SRP).
Set up your classes something like the following (base class User and multiple subclasses):
Then, create some sort of
UserManagerclass that implements an interface that looks like the following:The implementation of that method should load the passed user id’s information from the database, look at what type it is (partner, moderator, etc) and then instantiate the appropriate class and hydrate the appropriate information.