Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I know about Simple Factory Idiom, Factory Method and Abstract Factory Design patterns.

But I have two situations that I'm not sure how to call (PHP code example) :

class User {
  public static function LoadUserById($id) {
    $objUser = new User();
    //load details from DB
    return $objUser;
  }
}

class UserFactory {
   public function Create($id) {
    $objUser = new User();
    //load details from DB
    return $objUser;
   }
}

What are these two situations? Simple Factories (programming idiom) or are they called something else?

Is a good practice to name the class UserFactory? Isn't this something that might get confused with the A factory design pattern? Should I use different name for it like UserFinder?

When I think of the Factory Design Pattern I always think of examples where there are families of components derived from a parent class but it is clearly not the case here.

share|improve this question
add comment

1 Answer

The former one is called a violation of the single responsibility principle :) Your User class shouldn't know or care about the database. It is an anti-pattern, if anything.

There should be only one reason to change the User class - and it is that the concept of user within your application may change.

Implementing LoadUserById on the User class means that you'd have to rewrite that class for totally unrelated reasons - such as switching from MySQL to PostgreSQL, for example, which has nothing to do whatsoever with the user as such. Such implementation details should be detached, externalized.

The latter one is more of a Repository pattern than Factory, I believe. UserRepository could be a quite reasonable name for such a class.

Note that the role of a Factory is to create objects, especially whenever this task is complex and involves some advanced logic that you want to keep in one place.

Retrieving data from the database is a different responsibility. It's not about creating an object in itself - the real goal is obtaining data for that object (or "hydrating" it, as some insist).

share|improve this answer
    
Would the second one be an User data mapper? It takes the data from the DB and creates, creates and object, sets its properties and then returns it. –  MV. Dec 13 '13 at 6:14
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.