So when is the best time to use Factory Pattern.And can you guys give sample scenario.

Thank you very much in advanced.

TomB
—
2013-04-07T17:42:06Z —
#2

Firstly, using static methods as factories is self defeating.

One of the reasons for using factories is polymorphism. As soon as you call "User::load()" that flexibility is lost. If you replace that with " $factory->load() " then you have added flexibility, because $factory can be an instance of anything, not necessarily an instance of the User class. Also, grouping the object creation and the object implementation is a poor separation of concerns. A better method is this:

If that logic changes, say we add a "ModeratorUser" type, then the logic only needs to be updated in the factory. Everywhere that's creating users will remain unchanged and just call $factory->load($id);

Avram
—
2013-04-08T19:07:29Z —
#3

I'm using factory() in my ORM models all the time so I can chain methods in one line, e.g. $users = User::factory()->where('column', 'value')->limit(5)->get();

Php is slight different as it does not have overloading but named constructors can help by removing the need for default values be part of public api and confer what the construction means. Say for a response from a service instead of a boolean and a requirement to call other accessor to get the error out( quite boring to test and far less useful to return further back through the call chain ).

Or to allow the use of classes as constant values that can be passed safely at run time which have a guaranteed limited prevalidated set of values so do not need continual revalidating through the next steps in the call chain. eg.

This example draws paralells tohttp://sourcemaking.com/refactoring/replace-type-code-with-class and sometimes a later refactoring moves to replace type code with subclasses if further behaviour is required across the values. These may look similar to usual factories but it is a technique to remove primitives and allow small pieces of self validating behaviour to be put in their place.

These techniques are not used very often as they are quite small but can prove very useful as they are for the direct replacement of the new keyword. The first for clarity when an order of parameters means something in human terms, the second for flexibility in future refactoring and also the safety as it can be type hinted and trusted to behave accordingly without further checks from outside wherever it is passed.

Sometimes factory method and creation method are used interchangeably which can obscure it.

Tom is right that that factories are far more useful when injectable than static due to the mocking it allows and interchangeability using polymorhpism ). These examples are usually asserted against as a result from a method call.