Factory pattern advice needed

Hi,

I’ve been trying to incorporate the factory pattern into my current project, but I’m not sure how I should do it.

From what I have seen, there is 3 ways to utilize the factory pattern (abstract/method or something):

  1. As a method:

<?php
class User
{
    public static function factory($id)
    {
        return new User(DB:factory(), $id); 
    }
}
?>

  1. One factory class

<?php
class Factory
{
    public function __construct()
    {

    }

    public function user($id)
    {
        return new User($this->db(), $id); 
    }
}
?>

  1. One factory class per class to instantiate:

<?php
class UserFactory extends Factory
{
    public static function create($id)
    {
        return new User(DatabaseFactory:factory(), $id); 
    }
}
?>

I don’t like the first type because it hard codes the DB dependency. And the class will be directly called from my application (hard coded).

The second type will generate an enormous class (it has to have a method for all classes in the application) and if the generation of an object need other internal methods, it will be a mess.

The third type will double the number of classes in use (the number of files). The factory will be hardcoded within my code, just like the first type, however, with some abstraction.

Since you shouldn’t pass dependencies to other classes just for passing them further down in a different dependency, type 1 have to be hard coded somewhere… Type 2 doesn’t have that problem since you would naturally pass the factory if you need a dependency and that way that dependency could just be passed the same factory. Type 3 is similar to type 1 just that you hardcode the factory instead of the actual class.

I feel type 1 is out of the question since it fails with dependencies. Type 2 and 3 solves each others faults so I can’ make a choice between them…?

Would it be a viable option to do something like this:


<?php
class Factory
{
    $_instances = array();

    public function __construct()
    {
        
    }
    
    public function user($id)
    {
    return UserFactory::create($this->db(),$id);
    }
    
    public function db()
    {
    return DatabaseFactory::create();
    }
}

class UserFactory extends Factory
{
    public static function create(Database $db, $id)
    {
    return new User($db, $id);
    }
}

class DatabaseFactory extends Factory
{
    public static function create()
    {
    if (isset($this->_instances['db'])) return $this->_instances['db'];
    return $this->_instances['db'] = new Database;
    }
}
?>

Using this method I can easily pass the main factory class to my other classes that need to create an object and no object knows about other objects…

This is a simplified outline of what I’m trying to explain (How I think it should be. Based on my option above, but also identical for type 2 above.)


<?php
$url = '/user/profile/5';
$factory = new Factory;
$request = $factory->request($url);

    // $factory->request($url) internals
    return new Request($this, $this->router(), $url);
      
        // Request::__construct internals
        $this->factory = $factory;
        $this->current = $router->parseURL($url); // returns: array('controller' => 'user', 'action' => 'profile', 'params' => array(5));

$response = $request->exec()

    // $request->exec() internals
    $r = new ReflectionClass($this->current['controller']);
    $controller = $r->newInstanceArgs($this->factory, $this);
        
        // Controller constructor internals
        $this->factory = $factory;
        $this->request = $request;

    $action = $this->current['action'];
    $response = $factory->response();
    $response->attach($controller->$action($params));

        // Controller->action method internals
        $user = $factory->user($id)
        
            // $factory->user internals
            return new UserFactory($this, $id);

                // UserFactory internals
                return new User($factory->DB, $id);

        $view = $factory->view('user_profile');
        $view->user = $user;
        return $view;
       
    return $response;
    

$response->sendHeaders();

echo $response;
?>

This also works great with only type 2, but with type 3, I’m not sure how I should do it…?

Using that application outline, how would you do object creation and dependency injection? And does that application outline look ok? Should I structure it differently? What do you think?

From what I’ve seen in some frameworks, they either just don’t use any factory pattern, or they use type 1 (kohana). If there is something better or more elegant, or more “oop”, please tell me :smiley:

(Before anyone tells me to stop trying to reinvent the wheel and just use a well known framework and do whatever they do, please don’t. I’m trying to learn, and have enough time to do so.)

I’m sorry for this long post, and possibly the misunderstandings to come because of my not-so good English, but I hope I have made myself understood and that someone cares to give some input!

Thanks in advance! :slight_smile:

You make it sound way too complicated.

A normal factory pattern is just a static method that instantiates an returns an instance of its class. So your first example was the normal factory example.

Using a whole new class just to instantiate an object is nonsense.
use your first example but use the word “self” or better yet “static” if you using php 5.3

class User
{

 protected $db;
 protected $id;

public function __construct(DB $db, $id) 
{ 
   $this-&gt;db = $db;
   $this-&gt;id = $id;
} 
public static function factory($id) 
{ 
    return new self(DB:factory(), $id);  
} 

}

// for php 5.3 replace with
return new static(DB:factory(), $id);

This will allow you to extend class User and still reuse the factory in sub-class without having to define factory method again in sub-class

I don’t like the first type because it hard codes the DB dependency. And the class will be directly called from my application (hard coded).

The second type will generate an enormous class (it has to have a method for all classes in the application) and if the generation of an object need other internal methods, it will be a mess.

The third type will double the number of classes in use (the number of files). The factory will be hardcoded within my code, just like the first type, however, with some abstraction.

Since you shouldn’t pass dependencies to other classes just for passing them further down in a different dependency, type 1 have to be hard coded somewhere… Type 2 doesn’t have that problem since you would naturally pass the factory if you need a dependency and that way that dependency could just be passed the same factory. Type 3 is similar to type 1 just that you hardcode the factory instead of the actual class.

I feel type 1 is out of the question since it fails with dependencies. Type 2 and 3 solves each others faults so I can’ make a choice between them…?

Doesn’t that make you think maybe you don’t actually need what you’re trying to accomplish here? Is this the right way to take for your application?

Generally using factory instead or in addition to normal constructor is good practice but very often it is not needed. I remember in one particular famous book on refactoring the code it was recommended to use factory, but I can’t exactly remember the reason why. It has something to do with being able to make changes to the class or the library using your class easier later one, if case something changes. I still have this book in my Kindle, I will try to search for it.

Done wrong Factory patterning can lead to “busybox” code which slows the system down at no benefit, and makes learning whatever application that uses them that much harder. TomB and I had a very good debate on the pros and cons of the pattern in this forum if you want to do a forum search for it (I’m at work and don’t have time right now).

Like most patterns, knowing when NOT to use it is as important as when TO use it. Objects with simplistic or non existent setups do not usually need to be factoried. Rule of thumb - if the object takes no arguments at all at construct time, it probably doesn’t need a factory (it may need a way to abstract it’s instantiation, but this isn’t the same thing - a factory is an object that does nothing but make another object). If it has arguments, then the nature of those arguments comes into play. If it takes any objects as an argument a factory is likely a good idea. If its arguments are all primitives then it’s need for a factory is a judgement call depending on the complexity of the validation of those values and what the construct has to do to get the object into a ready state.

If you are writing actions into a constructor that could fail you should use a factory. At the end of __construct an object should be ready to go - that’s the purpose of __construct (and to a lesser extent unserialize/__wakeup). A factory can hold the logic for construction failure.

To some extent this is a discussion on separation of concerns. Factory patterns are good if the construction of the object is itself a large area of concern. But if it’s trivial (one line) using a factory is overkill.

That’s a very good point, Michael, and I totally agree with you!

I’ve never seen this and would advise strongly against it as it is a waste of time.

$user = User::factory();

Is every bit as much a bound dependency as

$user = new User();

That is, the static factory method is a complete waste of time - “busybox” code.

In a true factory pattern the factory is a separate object, and it’s only concern is the construction of user objects. Again, the goal is separation of concerns - a static method doesn’t accomplish this.

Michael, if I understand you correct, you are describing the type 3 factory as the only true factory pattern. I have some friends doing game development in c#/xna or something, and they say the same thing and recommended me to use that for all classes for consistency and abstract the object creation (even if the xFactory object only would return new X; since you never know what the future brings…

If you look at my proposed option, this would solve dependency and hardcoding issues I believe, but I can’t see how I can solve that by doing the pure factory pattern route?

What would be the best solution here?


<?php
class UserFactory extends Factory
{
    public static function create($id)
    {
        return new User(DatabaseFactory::create(), $id);
    }
}

$user = UserFactory::create(2);
?>


<?php
class UserFactory extends Factory
{
    public static function create($db, $id)
    {
        return new User($db, $id);
    }
}

$db = DatabaseFactory::create();
$user = UserFactory::create($db, 2);
?>


<?php
class UserFactory extends Factory
{
    public function create($db, $id)
    {
        return new User($db->create(), $id);
    }
}

$db = new DatabaseFactory;
$user = new UserFactory;
$user->create($db, 2);
?>

And if you look at my application outline, you can see that I’m passing the factory in wherever I need it. Using a pure type 3, would I pass the UserFactory in? or would I just hardcode UserFactory::create() wherever I need it? And since I only need one database connection, I guess it is the factory that should have the logic for having only one instance? right? that way I could easily change the desired behaviour to having two connection without changing anything in my application.

(btw, How does my application outline look? Does it look reasonable? If you ignore the factory part of it, since that is what we are here to figure out :))

Thanks again for your valuable feedback!

It’s not waste of time.

I think using separate class to be a “factory” class is a waste of time.

The reason to use factory as a static method is that it may be able to return not only the object of the same class but also a sub-class.

Consider something like this:

class User{

public static function factory(){

if(!empty($_COOKE[‘fb’]){
return new FacebookUser();
}

return new self();
}
}

The FacebookUser class extends User class. It may have couple of extra methods to allow working with Facebook API.

Now when user loggs in to your site, if user has cookie ‘fb’ you would instantiate a FacebookUser object.

Without factory method, it would be impossible to just add this logic into __construct() or User class because by the time __construct is called, the object is already created. Remember, __construct does not really create an object, instead it’s the first method called after the object is created.

But since if you use static factory method, then in the future, if you add support for Twitter API and want to allow users to login with Twitter, you simply modify your factory to return TwitterUser object if user has some type of specific cookie or some other condition. TwitterUser will also extend the User class.

So now, all your other classes in your application that were using User::factory() instead of just new User() dont have to be changed, they will just keep working as before. All because factory method makes it possible to instantiate sub-classes and not just the class.

Sure, you can take this whole logic and put it in yet another class… but why? Why create another class, why require to load one more class, allocating another memory space for another object?

Basically factory makes classes for flexible, making it easy to add some new login in the future. So if you think that there is a slight possibility that in the future you may sub-class your class, then using factory will make it sort-of “future proof”.

Again, it’s totally up to you how you want to do it. You may even invent a whole new programming pattern previously unknown to men. Php coding is very expressive, you can do the same thing a hundred different ways. If it works for you, and you like experimenting instead of using something that has already been invented and time-tested, then go for it.

One problem with using just a factory method is that if you need some other methods to instantiate the object, you will have to clutter the class with methods only related to object creation. Another problem is that you would either have to pass in dependencies just like you would if you just didn’t use a factory in the first place, or the factory method will have to know about dependencies, thus creating a hard coded dependency in that class (I don’t like that).

The big problem I see with this is that since you don’t know about future requirements, you could by passing dependencies break future compatibility, so you “have” to hard code the dependencies and what if object creation becomes more complex, requiring you to have multiple methods just related to object creation? I prefer smaller objects with very specialized roles, so I’d like to have object creation outside of the object itself…

Another possible problem about using a factory method is testing… I haven’t thought this one through so I may be mistaken here, but since we have decided to hard code dependencies (did we?), it would be problematic to swap out dependencies with dummy ones. With an external factory object, it would be relatively easy to overload certain objects with dummy ones.

Overload 1


$userfactory = new UserFactory;
$userFactory->setDatabase = $dummyDatabaseObject;
$user->create();

Overload 2


$db = new DummyDatabase;
DatabaseFactory::use($db);

$user = UserFactory::create();

DatabaseFactory::reset(); // or use(new RealDatabase) .. how doesn't matter that much

I’m not sure if a static factory would be preferable or not… The actual real world usage (see me application outline) is what I’m struggling with… I would really appreciate it if someone would take their time to modify my application outline (or parts of it) to show me how they would do it, keeping in mind that abstraction, flexibility and consistency in mind (performance is not that important).

Dependencies is usually a different topic, independent of your factory. It’s basically a whole separate strategy how you going to handle dependencies. Many projects use a so-called registry object. That object knows how to get other objects if and when you need them. Then you almost always have to pass just this one registry object to every new class either in factory or in constructor.

I think this is how it’s done in Symfony 2.0. It’s a pretty good pattern, I use it too, by the way. I found it to be the best solution. Basically there are not too many good solutions with dependencies in php. Older scripts used to rely on global namespace and use the old-fashined singleton pattern. This caused problems in testing.
Then a new pattern was introduced to use autoloader to create new classes (not just objects, but dynamically create classes) inside the autoloader function. This also did not stick in php community, many people were against this.

So, the registry object with the use of closures to handle singleton pattern is the latest and probably the greatest (so far) way to go with this.

I suggest you study Symfony 2 project, it’s pretty good, written by smart people. You can learn alot from it. Don’t try to invent something until you study great work of other smart people.

Hi,

Using a dependency injection container can really help with dependencies. The tradeoff they seem to be a little hard for people to understand. Once you wrap your head around it really helps deal with dependencies.

There are quite of few old threads that well document the use of a dependency injection.

Regards,
Steve

:nono:

So you intend to rewrite the parent each and every time a new subclass is introduced to the system in order to keep the code functional.

Absurdly and completely stupid.

My statement stands -

$user = User::factory();

is just as much a bound dependency as

$user = new User();

I - just no. :nono:

Yes, when new subclass is intrudoces you would rewrite the code in the super class’s factory method to add the possibility of using a new sub-class. But that’s all it takes - you rewrite it in only one place and all other classes that used the superclass::factory() don’t have to change, they don’t even have to know about it.

all other classess will keep using:
$user = User::factory()

and will always get the instance of User or a subclass of User. So if at any time a new type of user is introduces, other classes don’t have to change.

It’s just a matter of opinion. Some people like it. If you don’t like it, no one is forcing you to use it.

:rolleyes: You must have little to no experience with production code or enterprise level frameworking - because in that environment you have no idea how bad an idea that really is. :nono:

lampcms.com, you have done nothing to defend your position. The benefits of factories you mention are valid (polymorphism and abstracted dependency resolution). The only problem is the static method call, which you have done nothing to argue in favour of.

Static methods have an unknown global state, introduce hidden dependencies and because of this make testing difficult. Here is a good explanation of the problem: http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/

The simplest solution is to pass the factory (object) into the constructor of the class which requires it.

The link you provided clearly talks about Java code, a compiled language, very different from dynamic language like php. Second, even in Java factory pattern is not bad. In fact, it has been used in Java for much longer than in php, before php was even a OOP language. Like I said, if you don’t like factory pattern, don’t use it. Nobody is forcing you. But Factory method is actually recommended in the design pattern bood http://amzn.to/gMV4Kc (you know, that famous “gang of 4” book that many programmers treat like their bible).

So when you say “factory method is stupid”, you are saying something like “What do these Gang of 4 clowns know, they are stupid, I am smarter than them”

And what does the “unknown global state” means anyway? Something that you read on someone’s blog and thought it sounded “smart” ?

Again, the problem is not the factory pattern but the use of a static method to initialise it. These are two separate issues. Abstracting object creation out of application code is a good idea. Doing it via a static method is two steps forward and one step back. Did you even read the page I linked to? The fact that it refers to java is irrelevant. The programming practices are the same.

By “unknown global state” I mean you don’t know whether the globals used by the static method are correctly set up at the time of calling it.

Consider this:


class User {
	public static $db;
	
	public function __construct(DB $db) {
		//...
	}
	
	public static function factory() {
		return new User(self::$db);	
	}	
}

At any point you call User::factory() you have no idea whether User::$db is set up correctly. This goes for any global value.

Your example has something very specific. What you you don’t have public static $db in the class? I never said anything about having public static $db.

In your particular example, yes, bad design, but it’s not because of the factory pattern it’s because of public static $db

The only static method I mentioned is the factory method. That’s all, no static variables, only static factory method. Inside that factory methods is some logic that desides which sub-class of this class to return based on some conditions. Conditions could be passed to factory or could be extracted from some super-globals like $_COOKIE or $_GET or $_POST or even $_SERVER.

My Point is that you can easily change factory method if you have to, and it will not affect any other classes that call the factory() - they will still get the instance of this class, just different sub-class.

I explained it with example of different type of User object like user logged in with Facebook or With Twitter or with Linkein API - they all going to be sub-classes of User but still different types of objects. So if you adding another type of authentication like loging with Google account, all you have to do is add class GoogleUser which extends User and add 2 lines of code to factory to return GoogleUser IF some condition is detected (like some type of special cookie is passed in request hinting that this user is logged in with Google)

All these could be moved to a separate factory class, then you instantiate that class and pass it to constructors of other classes, but that’s just unnecessary. A single factory method in the superclass is perfectly fine.

For the third time, yes, the factory pattern is useful and addresses some very real problems. You don’t need to go over them again. There is no debate about the merits of moving object creation out of the business logic. I don’t know why you’re trying to create one.

Are you using the factory pattern to create objects which have dependencies? In any real-world system the answer will be yes or you’re not actually using factories where you should be. Where are they getting the dependencies from? Using static methods, the only answer to this is somewhere global. which [url=http://www.google.co.uk/url?sa=t&source=web&cd=9&ved=0CFoQFjAI&url=http%3A%2F%2Fwww.cs.usfca.edu%2F~wolber%2Fcourses%2F110%2Flectures%2Fglobals.htm&ei=YoJiTfiqOYit8gOLsNnxCA&usg=AFQjCNE0UQwlO_7AZ-MMe92lMWrlvHrNDg&sig2=ezh503_WToeQQfna89MPAw]is [url=http://misko.hevery.com/2008/08/25/root-cause-of-singletons/]bad.