Factory pattern advice needed

I understand what you saying. Dependency can be passed to factory. The way I do this is I use registry object and then just pass this one object to constructor or factory. That object knows how to get any of the objects that may be needed.

I never said that factory does not take any parameters - it does. In my case it takes Registry object.

Dependencies is a different topic. I am using the Registry object that uses so-called dependency injection pattern and closures for storing singleton instances when singleton is required.

lamp, when you have two different programmers (myself and Tom) who normally argue with each other constantly telling you that you’re doing something detrimental to your codebase you just might want to pay a little attention instead of brushing off their examples as irrelevant.

But pride before the fall I suppose. If you won’t learn from us you will learn the hard way - because your code is leading off to a mess.

You still haven’t given any counterargument of merit against my assertion - using User::factory() is in no way whatsoever better than simply using the new operator. You’re on the right track - get the object instantiation out of the main program logic and put it somewhere else… But somewhere else means just that - not a static method of the master class.

What you are doing is bloody busybox code with no purpose. None. What you are doing accomplishes nothing.

You make all this big talk about the merits of the factory pattern, but then you utterly fail to follow its pattern in any way. You’re attempt is as much a factory pattern as a rice-wagon is a stock car.

The only reason I’m willing to argue the point is I don’t want any novice programmers coming here and getting the wrong idea - you are advertising a lie and setting a horrid example.

A factory is an independent object. Done right the introduction of a new type of user should not mean anything the the factory class - it should be able to find the correct class out of the database or other data reference point.

It’s a matter of separation of concerns, pure and simple. My personal stance is factories are appropriate only for objects where their composition is an involved process. Once the decision is made to determine that a class is to have a factory it should be committed to.

Also, a factory does not have to have a 1:1 relationship with the classes involved. It is possible, even common, for a factory to be able to generate multiple disparate types of objects. I’ve even seen code bases where particularly complicated factories themselves are created by factories. Rare, but it happens and happens for a justifiable reason.

But putting the creation of an object into the static method of the utmost parent class is going to accomplish nothing.

Passing a dependency to the factory defeats the whole purpose of using it. You may as well just call new User($registry); How is the registry accessed? If you’re passing it as an object you’ve introduced a dependency on the registry into the client code. This is one of the things Michael Morris and I discussed in the thread he referred to earlier.

edit: Michael beat me to it :stuck_out_tongue:

Michael, no offence but I don’t think I have anything to learn from you. As I recall, you did not even know what Serializable interface was until I told you about it. That interface was in use in Java for many years and is still more advanced than in php. You were also acted like you discovered something new about Subject/Observer in SPL.

So, please, don’t tell me I should learn from you. I have learned enough from reliable good sources, sources I can trust.

Unlike you, I am not trying to convince anyone to do anything “my way”, I always say - there are many ways to do things in php, it’s very flexible, very expressive language.

As for passing dependency to factory - how does it defeat the whole purpose of factory, I don’t know.

so because someone has limited knowledge of one topic you dismiss their knowledge of every topic? Seriously? :rolleyes: There’s a name for that fallacy but I can’t be bothered to look it up.

Some of the most precious life lessons I’ve learned came from my 4 year old cousin. Only the arrogant, the foolish, and supremely stupid refuse to learn on the basis of the teacher. You demonstrate yourself to be all these things in this arrogant tripe, so to the ignore list you go.

I’m sorry I haven’t check the thread lately. I have been out of town.

I’m just getting confused about how I should do it :stuck_out_tongue: Everything seems logical, but then when I try to implement it, something tells me I’m doing it wrong…

This is how I think I should do it, based on your suggestions. Please correct me!


<?php
$url = '/user/profile/5';
$requestFactory = new RequestFactory;
$request = $requestFactory->create($url);

    // $requestFactory->create($url) internals
    $routerFactory = new RouterFactory;
    return new Request($routerFactory->create(), $url);
      
        // Request::__construct internals
        $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);
        
        // Controller constructor internals
        $this->request = $request;

    $action = $this->current['action'];
    $responseFactory = new ResponseFactory;
    $response = $responseFactory->create();
    $response->attach($controller->$action($params));

        // Controller->action method internals
        $userFactory = new UserFactory;
        $user = $userFactory->create($id)
        
            // $userFactory->create($id) internals
            return new User($id);

        $viewFactory = new ViewFactory;
        $view = $viewFactory->create('user_profile');
        $view->user = $user;
        return $view;
       
    return $response;
    

$response->sendHeaders();

echo $response;
?>

Is this way overkill? keeping in mind that there may be any number of subrequests (http/json/cli/internal), with any number of response types (json, html, xml) and any number of different parsing engines (routers).

How would you customize this application flow if needed?

My biggest concern now is that I’m hard coding the factories within an object. Is that good practice, or should I pass the factory in? (If so, wouldn’t I have to pass in every possible factory in the request object just so a controller can get them?). What do you think?

Again, Thank you for taking your time to answer my questions:)

It’s the right idea :slight_smile:

You’re right to suggest passing the factories in. Pass them in but make them more generic. For instance, User probably shares constructor and common base type with other models so create a ModelFactory rather than UserFactory/ProductFactory/BlogFactory etc.

In this:


 // $requestFactory->create($url) internals 
    $routerFactory = new RouterFactory; 
    return new Request($routerFactory->create(), $url)

It would be preferable to have $router as a variable in the request factory:


class RequestFactory {
	protected $router;
	
	public function __construct(Router $router) {
		$this->router = $router;
	}

	public function create($url) {
		return new Request($this->router, $url);
	}
}

This adds simplicity as it means your RouterFactory doesn’t care where its router comes from (It can be a factory higher up). The alternative to this, is giving your factories access to a Dependency Injection Container. However that’s a whole other topic.

My biggest concern now is that I’m hard coding the factories within an object. Is that good practice, or should I pass the factory in? (If so, wouldn’t I have to pass in every possible factory in the request object just so a controller can get them?). What do you think?

If this is the case, you’re not using factories at the point you should. Create a ControllerFactory (A generic one for any controller) which holds the dependencies which are required by controllers. This will prevent your entire system having a dependency on everything. It’s one of the things I provided examples for in the thread here: http://www.sitepoint.com/forums/showthread.php?t=708853 :slight_smile:

You’re certainly on the right lines though.

Tom

It’s the right idea :slight_smile:

You’re right to suggest passing the factories in. Pass them in but make them more generic. For instance, User probably shares constructor and common base type with other models so create a ModelFactory rather than UserFactory/ProductFactory/BlogFactory etc.

In this:


 // $requestFactory->create($url) internals 
    $routerFactory = new RouterFactory; 
    return new Request($routerFactory->create(), $url)

It would be preferable to have $router as a variable in the request factory:


class RequestFactory {
	protected $router;
	
	public function __construct(Router $router) {
		$this->router = $router;
	}

	public function create($url) {
		return new Request($this->router, $url);
	}
}

This adds simplicity as it means your RouterFactory doesn’t care where its router comes from (It can be a factory higher up). The alternative to this, is giving your factories access to a Dependency Injection Container. However that’s a whole other topic.

I totally agree. The only problem I can see using this method is that to use a request object, I now have to create a routerfactory and then make that create a router object to pass to the requestfactory and then finally get the request object… I can handle a few more lines of code, but what if there are multiple dependencies? I should probably implement some sort of DIC then, but how? I’ve been looking at kyberfabrikken’s article about this (http://blogs.sitepoint.com/2008/02/04/dealing-with-dependencies/), but can’t see how I should implement something like that using a factory class for each type of object without having to pass the container all over the place (should I be afraid of doing that?)

If this is the case, you’re not using factories at the point you should. Create a ControllerFactory (A generic one for any controller) which holds the dependencies which are required by controllers. This will prevent your entire system having a dependency on everything. It’s one of the things I provided examples for in the thread here: http://www.sitepoint.com/forums/showthread.php?t=708853 :slight_smile:

You’re certainly on the right lines though.

Tom

I don’t think I follow you here… If I understand you correctly, you want me to pass in a ControllerFactory to the Request object so that the Request object can use that to create the actual controller object without worrying about dependencies? That means that I have to hard code each dependency for each controller in that controllerFactory…? I’m not doing this in any other factory, so why now?

That controllerFactory would be seriously big to hold the creation logic for each controller… Each controller will have different dependencies, and I would then have to not only create the controller, but constantly updating this factory to match the current available controllers, making maintaining and developing… less fun :stuck_out_tongue:

I’m sorry if I misunderstood what you meant!

I’m really beginning to think that I should just stick the old non-factory/dic way of doing things. The more I learn about it and try to implement it, the more I miss the simple ‘new Object’ :stuck_out_tongue:

I totally agree. The only problem I can see using this method is that to use a request object, I now have to create a routerfactory and then make that create a router object to pass to the requestfactory and then finally get the request object.

What exactly is the ‘request’ object? A way of accessing get/post? Do you need to create them on the fly all the time? I’m guessing not so a factory is unnecessary. Create it at the top level of your program and pass it around.

Well ignoring the fact that in MVC the controller should have very few dependencies and looking at the problem at hand…

That controllerFactory would be seriously big to hold the creation logic for each controller… Each controller will have different dependencies, and I would then have to not only create the controller, but constantly updating this factory to match the current available controllers, making maintaining and developing… less fun

A Dependency inejection container could do this for you. However I would suggest looking at what dependencies each object has and whether it really needs them. Any dependency which exists for the sole purpose of being passed on to another object can be removed.

but can’t see how I should implement something like that using a factory class for each type of object without having to pass the container all over the place (should I be afraid of doing that?)

The factories would have access to the DIC, nothing else needs it.

What exactly is the ‘request’ object? A way of accessing get/post? Do you need to create them on the fly all the time? I’m guessing not so a factory is unnecessary. Create it at the top level of your program and pass it around.

The request object is supposed to generate a response object that holds the current request’s response. The top level request would open a controller that will be doing a lot more requests to finally build the page. (HMVC).

The idea is that if you visit a page, the controller you hit will only hold the layout and fill that layout with content from sub-requests. That way I can easily outsource some requests to a different server or even just load an entire different page within mine easily. If the request object detects a json request, the response object will return a json response etc…

Considering that there might be numerous requests, and they should be slightly different (jsonRequest, httpRequest, internalRequest), I believe a request factory is needed.

Well ignoring the fact that in MVC the controller should have very few dependencies and looking at the problem at hand…

A Dependency inejection container could do this for you. However I would suggest looking at what dependencies each object has and whether it really needs them. Any dependency which exists for the sole purpose of being passed on to another object can be removed.

True that controllers should have few dependencies, but there will most probably be at least 4 dependencies per controller:

  1. ViewFactory[]ModelFactory[]RequestFactory[*]Current Request object

And considering the amount of controllers I will end up with by going the hmvc route (one controller per “widget”/section of the site), that controllerFactory will not look pretty…

(Just so I understand you correctly, the ControllerFactory should be something like this, right?)


<?php
class ControllerFactory
{
    public function __construct { }
    public function blog { }
    public function index { }
    public function user {*} // from my application example
}
?>

If so, I could of course just have some magic functions (__call) to create different controllers so I avoid the nightmare of updating it every time I add or change a controller. Valid solution? That would solve a lot…

The factories would have access to the DIC, nothing else needs it.

But how?


<?php
class RequestFactory {
    public $dic;
    
    public function __construct(DIC $dic)
    {

    }
}
?>

Using the requestfactory in the controller now would require the controller to first create a DIC object (It should probably be a singleton…)?

If so, I could of course just have some magic functions (__call) to create different controllers so I avoid the nightmare of updating it every time I add or change a controller. Valid solution? That would solve a lot…

Yep, in fact that’s desirable. An alternative is $factory->create(‘User’); Sending parameters to the factory is useful. __call is an option also, but that will be just down to preference, well defined class API vs debatably nicer looking client code.

Using the requestfactory in the controller now would require the controller to first create a DIC object (It should probably be a singleton…)?

Well in most systems there is a top level boostrap and/or front controller which deals with the set up of top level classes such as configuration settings, DIC, potentially autoload, etc. This is where your DIC would be initialised along with most of the factories you might want to pass around).


<?php 
$url = '/user/profile/5'; 
$routerFactory = new RouterFactory;
$responseFactory = new ResponseFactory;
$controllerFactory = new ControllerFactory(new ViewFactory, new ModelFactory /*, new RequestFactory infinite loop*/); //<-------------------- ?????
$requestFactory = new RequestFactory($routerFactory, $controllerFactory, $responseFactory); 
$request = $requestFactory->create($url); 

    // $requestFactory->create($url) internals 
    $controllerFactory->setRequestFactory($this);   // <-------------------- ?????
    return new Request($this->routerFactory, $this->controllerFactory, $this->responseFactory, $url); 
       
        // Request constructor internals 
        $this->current = $routerFactory->create()->parseURL($url); // returns: array('controller' => 'user', 'action' => 'profile', 'params' => array(5)); 
        $this->controllerFactory = $controllerFactory;
        $this->responseFactory = $responseFactory;

$response = $request->exec(); 

    // $request->exec() internals 
    $controller = $this->controllerFactory->create($this->current['controller'], $this);
         
        // $this->controllerFactory->create() constructor internals
        $r = new ReflectionClass($controller); 
        return $r->newInstanceArgs($currentRequest, $this->requestFactory, $this->viewFactory, $this->modelFactory);
    
            // Controller constructor internals 
            $this->currentRequest = $currentRequest; 
            $this->requestFactory = $requestFactory;
            $this->viewFactory = $viewFactory;
            $this->modelFactory = $modelFactory;

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

        // Controller->action method internals 
        $user = $this->modelFactory->create('user', $id); 
         
            // $modelFactory->create('user', $id) internals 
            return new UserModel($id); 

        $view = $this->viewFactory->create('user_profile'); 
        $view->user = $user; 
        return $view; 
        
    return $response; 
     

$response->sendHeaders(); 

echo $response; 
?>

This is what I have now, and I kind of like it…:slight_smile:

However I have some questions about it:

  1. Take a look at where I create the controllerFactory and the internals of requestFactory. There is an infinite dependency loop there… I just can’t figure out what to do with it… :s I figure I need a DIC to solve this?

  2. If I require a singleton Router (example), the routerFactory would be responsible for creating only one instance, right? (Since I have no DIC)

3a. If you look at where my controller is created in the controllerFactory, would it be OK to pass those dependencies to the ‘new controller’ even if that specific controller don’t need them? I have already created those dependencies (objects)… Shouldn’t I create dependencies only IF they are needed?

I know that creating those factories doesn’t cost much resource wise, but for the sake of being correct, they are a waste if the controller only returns ‘hello world’ or something like that (without subrequests and models).

3b. Kind of related to 3a. What if the request ($url) is external, which means that the request object doesn’t create controllers, only uses curl (example) to fetch an external website. The controllerFactory has been created for nothing, thus again wasting resources.

  1. Am I improving my application? :stuck_out_tongue:

Thanks again! :slight_smile:

Sorry for the delayed reply.

  1. Take a look at where I create the controllerFactory and the internals of requestFactory. There is an infinite dependency loop there… I just can’t figure out what to do with it… :s I figure I need a DIC to solve this?

Why does the controller need the request (or factory for it)? Do you ever have more than one request object for any given page view? If so, what does this achieve?

Perhaps my advocation of the factory pattern was a little overstated. Where possible, it’s almost always preferable to pass in a fully constructed object than a factory which can create it. Only use a factory when the object you’re creating needs constructor parameters from the client code.

Look at why you’re using a factory. If it’s just to avoid passing the dependency itself around then the factory can be removed and the dependency passed directly.

  1. If I require a singleton Router (example), the routerFactory would be responsible for creating only one instance, right? (Since I have no DIC)

Factories may be overkill for top level framework initialisation code. If you do choose to use them here the factory should only exist at that level. If you’re using the factory purely to access a single instance of an object just skip the middle man and pass the object around.

3a. If you look at where my controller is created in the controllerFactory, would it be OK to pass those dependencies to the ‘new controller’ even if that specific controller don’t need them? I have already created those dependencies (objects)… Shouldn’t I create dependencies only IF they are needed?

It’s a judgement call. Some controllers may never need to access models but it’s probably worth giving them the option because most controllers will. However, if you are using constructor parameters and reflection in the way you are, it should be easy enough to build different types of controller into the factory.

  1. Am I improving my application?

This is the biggest question and easily open to debate :stuck_out_tongue: The point in moving object creation logic out of client code is flexibility which should allow for easier testing and faster future developments. Of course this comes at the cost of more complex code and a longer initial development time. Whether the trade-off is worth it will depend on the scale of the project, how often things are likely to change and your development procedures. If you’re using TDD for instance, this flexibility makes development far easier.

Why does the controller need the request (or factory for it)? Do you ever have more than one request object for any given page view? If so, what does this achieve?

One controller (in my application atleast) will often only consist of a single element on the web page (e.g One controller returns the menu, another one the login form, a third one the latest headlines, and so on).

This way, I can easily use ajax to update certain parts of the webpage. My different webpages (pageviews) actually consists of one controller putting everything together and a lot more controllers to build up the page (Think widgets).

Instead of doing this by just using the controllerfactory directly (and remove request factory as dependency), I figured it would be neat to do it the exact same way as the application itself does it (By creating a Request (object) which returns a Response (object)). Another reason for doing it this way is that the request object uses the router to figure out what to do when requesting an url (is it an external request: Use curl to fetch the response. Internal request? Use controllers/Actions. CLI request? etc.). Since the controller which is created within the requestobject has access to it’s requestobject, they will know if they are requested internally or externally, etc. A pageview may consist of multiple request objects this way.

Of course it will not be the best performance by doing this (not too big of an performance impact though), but it will be easy to scale out by running some widgets on a different server just by changing the request object (probably by parsing the requested url so the factory generates the correct request object).

Sounds valid? I haven’t found a better way to fix this loop in the factory creation yet, and I just can’t let it be like it is now… I’m thinking of just moving the entire creation of controllerfactory into the requestfactory (see last quote).

Factories may be overkill for top level framework initialisation code. If you do choose to use them here the factory should only exist at that level. If you’re using the factory purely to access a single instance of an object just skip the middle man and pass the object around.

I agree, but from a theoretical standpoint, it would be the factory that has the responsibility of only allowing one instance? If I’m correct, that would mean that if you have no DIC, the factory itself would hold the singleton instance and act as a container?

It’s a judgement call. Some controllers may never need to access models but it’s probably worth giving them the option because most controllers will. However, if you are using constructor parameters and reflection in the way you are, it should be easy enough to build different types of controller into the factory.

I don’t have to create the model if the controller doesn’t need it, but I still have created the factory for the model… I’m probably way overthinking this, but since I’m creating un-needed objects, wouldn’t that mean that I may need to rethink my object creation logic? Perhaps I should have a controllerfactoryFactory to avoid this (I will not do that since that is way overkill, but in theory, that would be correct right)?

Since I’m not sure I need a controllerfactory at all (I only need it if requestFactory returns a InternalRequest object. In reality, this is a highly unlikely scenario as the requested url will almost always go to a controller for putting together a page or returning something, so I’m), I think it could be argued that the creation of a controllerfactory could consist within the requestfactory… I’m not happy with that either, but when it also solves my initial controller/request-factory loop dependency, I’m starting to feel that this is the only way of doing it to make it as ‘correct’ as possible.

I figured it would be neat to do it the exact same way as the application itself does it (By creating a Request (object) which returns a Response (object)). Another reason for doing it this way is that the request object uses the router to figure out what to do when requesting an url (is it an external request: Use curl to fetch the response. Internal request? Use controllers/Actions. CLI request? etc.). Since the controller which is created within the requestobject has access to it’s requestobject, they will know if they are requested internally or externally, etc. A pageview may consist of multiple request objects this way.

The common method is to create a router for url mapping and a dispatcher for calling the correct controller action and setting up the MVC triad. In this scenario only the dispatcher would know of the controller factory (or just act as a type of factory itself and create the controllers). The dispatcher could potentially be called from anywhere in the system.

What I cant see is why your controllers require the request object or what purpose the request object really serves other than a container for each triad. Also, why does a controller care how it was created? Imho this is a separation of concerns issue and the heart of the problem you’re facing.

Saying that, cyclic references aren’t always bad. It’s best to avoid them where possible but sometimes they are the best option.

I agree, but from a theoretical standpoint, it would be the factory that has the responsibility of only allowing one instance? If I’m correct, that would mean that if you have no DIC, the factory itself would hold the singleton instance and act as a container?

A factory generally would not have responsiblity for ensuring a single instance. A DIC used by the factory might, however. The way this would be achieved is through a singleton. However, if you only want one instance of something, skip the factory. Create the instance and pass it around directly.

This again, is separation of concerns. Code using your “singleton” object should not care where it came from or whether the object is a single instance or not.

The common method is to create a router for url mapping and a dispatcher for calling the correct controller action and setting up the MVC triad. In this scenario only the dispatcher would know of the controller factory (or just act as a type of factory itself and create the controllers). The dispatcher could potentially be called from anywhere in the system.

What I cant see is why your controllers require the request object or what purpose the request object really serves other than a container for each triad. Also, why does a controller care how it was created? Imho this is a separation of concerns issue and the heart of the problem you’re facing.

Saying that, cyclic references aren’t always bad. It’s best to avoid them where possible but sometimes they are the best option.

I don’t follow you on the difference between my request object and the dispatcher… Are they not exactly the same thing? From my understanding, they at least seem very similar, creating controllers OR ‘dispatching’ to an external url?

You say that the dispatcher could potentially be called from anywhere in the system, isn’t that against dependency injection practice/global namespace? And how would the dispatcher be the only thing that knows about controllerFactory (Should you set up the factory within the dispatcher, instead of passing it in?)?

The only reason for controllers knowing about the (current) request object is that some controllers may want to know if they are being access by ajax, post, get or put etc. The request object would also for example hold accepted languages from the request which a controller might be interested in. I thought it may be useful to use the request object to hold information related to the request which may or may not be of interest to the controller, or be useful when doing a sub-request (e.g. external url). I may be doing something really stupid by doing this. I just found it reasonable to do it like this…

A factory generally would not have responsiblity for ensuring a single instance. A DIC used by the factory might, however. The way this would be achieved is through a singleton. However, if you only want one instance of something, skip the factory. Create the instance and pass it around directly.

This again, is separation of concerns. Code using your “singleton” object should not care where it came from or whether the object is a single instance or not.

The highlighted part is exactly what I thought, hence why I thought a factory should be involved in creation of singeltons as well. It just feels strange to use factories everywhere and don’t do it with singeltons just because they are singeltons (which shouldn’t be any different from regular objects in regards to needing creation logic or different requirements in the future). I guess it comes down to personal preference, but I don’t think I would mind about the extremely small overhead by having a simple factory for singeltons as well just to increase consistency.

I don’t follow you on the difference between my request object and the dispatcher… Are they not exactly the same thing? From my understanding, they at least seem very similar, creating controllers OR ‘dispatching’ to an external url?

I’m just trying to understand how your system is working. They may well be the same.

You say that the dispatcher could potentially be called from anywhere in the system, isn’t that against dependency injection practice/global namespace?

Well anywhere that needs it. How it’s passed around is a separate issue but for example it’s useful for a view to initiate an MVC triad. The dispatcher gives a common interface to the initialisation logic so it can be re-used for example from a view, the URL router or anything else which might need it.

And how would the dispatcher be the only thing that knows about controllerFactory (Should you set up the factory within the dispatcher, instead of passing it in?)?

That was perhaps a little conservative, but the controllerFactory itself probably has no reason to be passed around the system other than to the dispatcher from your boostrap code/entry point.

I thought it may be useful to use the request object to hold information related to the request which may or may not be of interest to the controller, or be useful when doing a sub-request (e.g. external url). I may be doing something really stupid by doing this. I just found it reasonable to do it like this…

Generally, in OOP if you’re describing what a class is for and use the word “And”, it’s doing too much and should be split.

If you split your request object into a dispatcher and details about the request (get/post, etc) does this solve the problem?

I’m not sure it would, however, because the controller may still need to call the dispatcher. What I still can’t understand is why your request object requires a reference to controllers it’s created. Wouldn’t removing this reference fix the circular referencing issue?

The highlighted part is exactly what I thought, hence why I thought a factory should be involved in creation of singeltons as well. It just feels strange to use factories everywhere and don’t do it with singeltons just because they are singeltons (which shouldn’t be any different from regular objects in regards to needing creation logic or different requirements in the future). I guess it comes down to personal preference, but I don’t think I would mind about the extremely small overhead by having a simple factory for singeltons as well just to increase consistency.

If Michael hasn’t been annoyed out of the topic by lamp, I’m sure he’ll come in and argue against this. And I’d agree with him.

The application has to be initialized somewhere.

This code is entirely redundant:


$factory = new Factory($someDependency);
$foo = $factory->create('foo');

it can be replaced with:


$foo = new Foo($someDependency);

If you’re creating a factory, using it within the same scope and never using it again, there is zero benefit to its use.

As you say, the only potential argument is consistency. But if you extrapolate from that, you need a factory to create your factories and a factory to create that. ad infinitum.

The factory pattern doesn’t exist to eliminate the new keyword. It exists to allow client code to work without worrying about correctly initilising the (correct type of) object. Since the top level of code’s sole job is object initialisation and set up I’d argue that a factory is redundant here.

Of course it won’t harm the system per se (it will introduce additional complexity and a negligible performance hit though) but won’t add any benefit either.

The real answer is a DIC. Let the DIC create the singletons when something that needs them is created.

If not using a DIC, all the dependencies these objects should need are created at the same top level and are available in current scope.

I just want to add a quick disclaimer to all of this theory:
As we’ve seen, it’s possible to attempt to find the best solution and spend a lot of time doing so. Firstly, there’s no one-size fits all approach and generally no ‘correct’ answer, only best practices. Secondly, and more importantly, spending a long time over-analysing small implementation details like these can be detrimental to the timely completion of the project :stuck_out_tongue:

Hadn’t been annoyed away, just didn’t have anything to add.

In my own framework I use a class called StartUp. Call it a bootstrapper, or a dependency injection container or whatever, it’s goal is to get the framework ready to go. The framework itself doesn’t interface with Startup - it has only one public method and that method won’t allow itself to be called more than once - essentially making it a ‘main’ function like in C.

The configuration file names off the classes that will serve as dispatchers, views, models and so on to the degree needed to start the system. As a result no class is directly invoked by the new operator at startup time. StartUp itself, being entirely static, also doesn’t get hit by new (it does have a constructor that throws a fatal error if someone tries to make a startup object).

Once the framework runs the Startup kicks the objects into APC Cache for reuse so that it doesn’t have to reference the configuration file repeatedly.

I’m not against new Object(), but I only use such code at the highest level - such as for a particular client project. In the lower levels of the framework, where behaviors need to be reconfigured, the direct use of new would block that.

But it should be noted that StartUp isn’t a pure factory in the sense that it can be extended to allow arguments to be modified. The arguments of the dispatchers are pretty much set in stone.

At the top level only the Control dispatcher sees the model and the view dispatchers. The event controllers pair up a view that knows what the output is to a model that has data, then lets the view freely talk to it and steps out of the way.

But at this point we are moving out of Factory pattern discussion to MVC in general (again).

If you split your request object into a dispatcher and details about the request (get/post, etc) does this solve the problem?

Didn’t think about that. Sounds logical though. Have to play with the idea and see what I can come up with. This would basically make the dispatcher a kind of controllerfactory factory since it would contain the logic to either, use the controllerfactory to create a controller, or make an external request (probably by using a different factory) if I’m not missing anything. I agree with you that objects shouldn’t do too much so this may be a good idea.

I’m not sure it would, however, because the controller may still need to call the dispatcher. What I still can’t understand is why your request object requires a reference to controllers it’s created. Wouldn’t removing this reference fix the circular referencing issue?

The request object doesn’t need a reference to the controller, it needs the controller factory to create controllers. The controller factory need a request factory (which needs a controller factory, which needs a request factory etc etc) to allow controllers to make requests. I can’t see how splitting the request object into a dispatcher and a request object would change anything in the regard as a dispatcher would need a controller factory which would need a dispatcher factory… I could possibly remove the need for a request/dispatcher factory by just passing the current request object to the controller and in the controller do something like: $this->request->subrequest(‘/user/stats’); and then let the request object use the requestfactory to create a new request (this way I could easily create a requests tree showing how a specific page is built up. Probably easy anyway though :p)

The application has to be initialized somewhere.

This code is entirely redundant:


$factory = new Factory($someDependency);
$foo = $factory->create('foo');

it can be replaced with:


$foo = new Foo($someDependency);

If you’re creating a factory, using it within the same scope and never using it again, there is zero benefit to its use.

As you say, the only potential argument is consistency. But if you extrapolate from that, you need a factory to create your factories and a factory to create that. ad infinitum.

The factory pattern doesn’t exist to eliminate the new keyword. It exists to allow client code to work without worrying about correctly initilising the (correct type of) object. Since the top level of code’s sole job is object initialisation and set up I’d argue that a factory is redundant here.

Of course it won’t harm the system per se (it will introduce additional complexity and a negligible performance hit though) but won’t add any benefit either.

I totally agree with you, especially if you are using it top-level or in the same scope. My point was just that there probably is useful to use a factory if you now (or in future) may need to change creation logic to support different objects (like HTTP_Router or CLI_Router based on for example current type of request) or maybe switch away from singeltons (bad example, I know, but my point is still valid I think).

The real answer is a DIC. Let the DIC create the singletons when something that needs them is created.

Would a DIC hold factories or only regular objects? If the latter, is a DIC really only useful for singelton objects?

Would a DIC hold the identity map object (for example for user objects) or act as an identity map? I would bet money on the first one. Just have to make sure :slight_smile:

I just want to add a quick disclaimer to all of this theory:
As we’ve seen, it’s possible to attempt to find the best solution and spend a lot of time doing so. Firstly, there’s no one-size fits all approach and generally no ‘correct’ answer, only best practices. Secondly, and more importantly, spending a long time over-analysing small implementation details like these can be detrimental to the timely completion of the project :stuck_out_tongue:

Very true, but isn’t half of the fun getting everything just right by over-analyzing (and learning of course) :wink: I wouldn’t use this much time on a serious project though. I like discussions like these since you learn a lot from it!