Factory Design Pattern
Design Patters part 1.
I built these samples on PHP design patterns a while ago to make some friends write better code. They ignored it, so I give it to you. I hope they are self-explanatory. If not: Feel free to ask!
First off: The factory design pattern. It encapsulates the creation of a class so an object can be instantiated using the factory’s create-method rather than the class’ constructor. This comes in handy if you’re planning to extend your application (usually you are) and don’t want to change every call to your class’ constructor.
//------------------------------------------------
// Factory: The "factory pattern" creates an object
// using a method rather than a constructor
//------------------------------------------------
// Definition
class MyClass
{
public $content = "Hello world!\n";
}
class MyClassFactory
{
public function Create()
{
return new MyClass();
}
}
// Usage
$myObject= MyClassFactory::Create();
echo $myObject->content; // "Hello world!"