vendredi 21 août 2015

How to implement factory design pattern

I am learning about design patterns and I'm at a point where they start making sense but still kind of look like a bunch of nonsense, so please bare with me.

I am trying to apply the factory design pattern to a real world problem in an application. I am using data objects (kind of like ORM but not quite) where an object represents a row from the database and its properties are the columns. Having said this - I have 3 different types of users which all extend the base class User and are all kept in the same database table of users. I have an extra column type that I use to determine the type of user.

So to fetch a user with id 1 I would use this code:

$user = User::getByPK(1);

However the different types of users have different properties and methods and I need to get the appropriate instance, which is where I am stuck. I created a factory class but I am not quite sure how to call it. I need to have the information about the user from the database before I can determine what type of user it is, however I need to instantiate the appropriate class and these two things are kind of dependant of each other.

Here is what I made - I get the appropriate instance but all of the information for the user is kept in the base class.

class UserFactory {

    public function getUser($type) {

        switch($type) {
            case User::ORDINARY:
                return new OrdinaryUser();

            case User::MODERATOR:
                return new Moderator();

            case User::ADMINISTRATOR:
                return new Administrator();
        }
    }
}


$user = User::getByPK(1); // Has all the information

$factory = new UserFactory();

$object = $factory->getUser($user->type); // Is instance of Administrator

What is the proper way to use the factory pattern in this case?

Aucun commentaire:

Enregistrer un commentaire