3

I'm trying to understand why object should be created using factories and not new operator? For example:

$validatePost = Validation::factory($_POST);

instead of

$validatePost = new Validation($_POST);

The static method factory of the class does exactly the same:

public static function factory(array $array)
    {
        return new Validation($array);
    }
Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488
  • Recommend reading the book you see here: http://en.wikipedia.org/wiki/Design_Patterns – vee Oct 07 '13 at 06:19
  • Thanks, so is it just following the pattern or there was a good reason to do that? – Max Koretskyi Oct 07 '13 at 06:22
  • 2
    I deleted my other comment and would rather recommend you to read this: http://en.wikipedia.org/wiki/Factory_method_pattern. Not really fond of Wikipedia myself but this should give you some understanding. But really recommend you to read that book(say 20 times). I've read it about 50 times already! – vee Oct 07 '13 at 06:27

3 Answers3

3

as per following question :

Constructors vs Factory Methods

Use the Factory Method pattern when

a class can't anticipate the class of objects it must create
a class wants its subclasses to specify the objects it creates
classes delegate responsibility to one of several helper subclasses, and you want to             
localize the knowledge of which helper subclass is the delegate
Community
  • 1
  • 1
Sunil Verma
  • 2,490
  • 1
  • 14
  • 15
2

This way you have one method all objects are created with. And if you need to add additional functionality to creating, for example, Models, you just override original factory() method with your own in the application folder.

Denis Petrov
  • 117
  • 1
  • 6
1

It's important to note that the reasons cited in Sunil's answer (from the linked discussion) refer to the "classic" GoF factory pattern, which is not the same as what the question is about here.

(For example, "class can't anticipate the class of objects it must create" doesn't apply here, where everything is statically determined.)

The static factory technique can be used for different purposes, e.g. typically for various flavors of "finitons" (incl. singletons, where n = 1), or to encapsulate centralized (or otherwise nontrivial) resource management, or for the architectural flexibility reason Denis mentioned in his answer; etc.

Sz.
  • 3,342
  • 1
  • 30
  • 43