A factory creates an object. So if you want to build
class A{ public $classb; public $classc; public function __construct($classb, $classc) { $this->classb = $classb; $this->classc = $classc; } }
You will not want to rely on the need to execute the following code each time you create an object
$obj = new ClassA(new ClassB, new Class C);
There will be a factory. We define a factory to take care of this for us:
class Factory{ public function build() { $classc = $this->buildC(); $classb = $this->buildB(); return $this->buildA($classb, $classc); } public function buildA($classb, $classc) { return new ClassA($classb, $classc); } public function buildB() { return new ClassB; } public function buildC() { return new ClassC; } }
Now all we have to do is
$factory = new Factory; $obj = $factory->build();
The real advantage is when you want to change the class. Let's say we wanted to pass another ClassC:
class Factory_New extends Factory{ public function buildC(){ return new ClassD; } }
or new ClassB:
class Factory_New2 extends Factory{ public function buildB(){ return new ClassE; } }
Now we can use inheritance to easily change the way a class is created, to introduce a different set of classes.
A good example would be this user class:
class User{ public $data; public function __construct($data) { $this->data = $data; } }
This $data class uses the class we use to store our data. Now for this class, let's say we use a session to store our data. factory will look like this:
class Factory{ public function build() { $data = $this->buildData(); return $this->buildUser($data); } public function buildData() { return SessionObject(); } public function buildUser($data) { return User($data); } }
Now, let's say, instead we want to store all our data in a database, it is very simple to change it:
class Factory_New extends Factory{ public function buildData() { return DatabaseObject(); } }
Factories is the design pattern that we use to control the union of objects, and using the right factory patterns allows us to create custom objects that we need.