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.
1 Answer 1
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).
-
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.– MV.2013年12月13日 06:14:02 +00:00Commented Dec 13, 2013 at 6:14