<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Creational Pattern &#8211; Simon Jakowicz</title>
	<atom:link href="https://www.jakowicz.com/tag/creational-pattern/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.jakowicz.com</link>
	<description>Just another blogger</description>
	<lastBuildDate>
	Sat, 05 Dec 2026 18:20:01 +0000	</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=5.1.19</generator>
	<item>
		<title>Prototype Pattern in PHP</title>
		<link>https://www.jakowicz.com/prototype-pattern-in-php/</link>
				<comments>https://www.jakowicz.com/prototype-pattern-in-php/#respond</comments>
				<pubDate>Sat, 12 Apr 2014 12:32:56 +0000</pubDate>
		<dc:creator><![CDATA[Simon]]></dc:creator>
				<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[OOP]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Creational Pattern]]></category>
		<category><![CDATA[Prototype Pattern]]></category>

		<guid isPermaLink="false">http://www.jakowicz.com/?p=835</guid>
				<description><![CDATA[This is post 6 of 13 in the series &#8220;PHP Design Patterns&#8221; Next up is the final creational pattern I&#8217;m going to cover in this series. It&#8217;s the prototype pattern&#8230;. it&#8217;s literally beyond simple, so let&#8217;s get going. What is the prototype pattern The concept behind the prototype pattern is to create objects by cloning... <a class="more-link" href="https://www.jakowicz.com/prototype-pattern-in-php/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
								<content:encoded><![CDATA[<aside class="wp-post-series-box series-php-design-patterns">
	<p class="wp-post-series-name">
		This is post 6 of 13 in the series <em>&ldquo;PHP Design Patterns&rdquo;</em>	</p>

	
	</aside>
<h2>Next up is the final creational pattern I&#8217;m going to cover in this series.</h2>
<p>It&#8217;s the prototype pattern&#8230;. it&#8217;s literally beyond simple, so let&#8217;s get going.</p>
<p><span id="more-835"></span></p>
<h2>What is the prototype pattern</h2>
<p>The concept behind the prototype pattern is to <span class="snippet">create objects by cloning existing objects instead of initialising new objects.</span> I haven&#8217;t actually benchmarked this myself in PHP to see the benefit, however <span class="snippet">cloning is for sure less processor intensive</span> &#8211; I&#8217;ll get onto why in a bit. That isn&#8217;t to say objects should always be cloned. Unless you&#8217;re creating hundreds or more objects of the same class, you&#8217;re probably not going to notice any difference.</p>
<p>Cloning objects in PHP is extremely easy due to its magic __clone()  method and the clone keyword.</p>
<h2>Rules</h2>
<ol>
<li>Make sure the class of the object being class being cloned has a public __clone() magic method. It doesn&#8217;t matter if their is no content to the method.</li>
</ol>
<h2>Advantages</h2>
<ol>
<li>The time taken to clone an object is quicker than it would be to initialise a new object. This is because when an object is cloned the constructor is not re-executed.</li>
</ol>
<h2>Drawbacks</h2>
<ol>
<li>When an object is cloned the constructor is not re-executed. Constructors should not deal with any business logic other than maybe setting some variables. So this shouldn&#8217;t be a problem anyway, but if you&#8217;re working on a legacy code base, this is worth taking into consideration.</li>
</ol>
<h2>Example</h2>
<pre class="prettyprint linenums">
/**
 * A class to represent the CocaCola drink
 */
class CocaCola {
    
    private $fizzy;
    private $healthy;
    private $tasty;

    /**
     * init a CocaCola drink
     */
    public function __construct() {
        $this->fizzy   = true;
        $this->healthy = false;
        $this->tasty   = true;
    }

    /**
     * This magic method is required, even if empty as part of the prototype pattern
     */
    public function __clone() {
    }

}

$cola = new CocaCola();

/*
 * object(CocaCola)#1 (3) {
 *   ["fizzy":"CocaCola":private]=>
 *   bool(true)
 *   ["healthy":"CocaCola":private]=>
 *   bool(false)
 *   ["tasty":"CocaCola":private]=>
 *   bool(true)
 * }
 */
var_dump($cola);

$colaClone = clone $cola;

/*
 * object(CocaCola)#2 (3) {
 *   ["fizzy":"CocaCola":private]=>
 *   bool(true)
 *   ["healthy":"CocaCola":private]=>
 *   bool(false)
 *   ["tasty":"CocaCola":private]=>
 *   bool(true)
 * }
 */
var_dump($colaClone);
</pre>
<h2>Conclusion</h2>
<p>Thats it. Pretty simple ayyy! This admittedly isn&#8217;t the best use case, but I didn&#8217;t want to complicate something, which is so simple. <span class="snippet">The prototype pattern really comes into it&#8217;s own, when the constructor starts doing any kind of work and by using cloning, you only have to make one call to the constructor.</span> Constructors should never do anything but set values anyway, but if setting these values means calling complex expressions. This is something you would be better off only doing once, instead of thousands of time or more.</p>
]]></content:encoded>
							<wfw:commentRss>https://www.jakowicz.com/prototype-pattern-in-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
							</item>
		<item>
		<title>Builder Pattern in PHP</title>
		<link>https://www.jakowicz.com/builder-pattern-in-php/</link>
				<pubDate>Sun, 06 Apr 2014 13:14:17 +0000</pubDate>
		<dc:creator><![CDATA[Simon]]></dc:creator>
				<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[OOP]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Builder Pattern]]></category>
		<category><![CDATA[Creational Pattern]]></category>

		<guid isPermaLink="false">http://www.jakowicz.com/?p=815</guid>
				<description><![CDATA[This is post 5 of 13 in the series &#8220;PHP Design Patterns&#8221; The builder pattern is another creational pattern, meaning its purpose is the creation of objects. Similar to the purposes of Singleton, Multiton and Factory patterns. However the builder pattern will not only create objects, but prepare them for your application too. The builder... <a class="more-link" href="https://www.jakowicz.com/builder-pattern-in-php/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
								<content:encoded><![CDATA[<aside class="wp-post-series-box series-php-design-patterns">
	<p class="wp-post-series-name">
		This is post 5 of 13 in the series <em>&ldquo;PHP Design Patterns&rdquo;</em>	</p>

	
	</aside>
<h2>The builder pattern is another creational pattern, meaning its purpose is the creation of objects. Similar to the purposes of Singleton, Multiton and Factory patterns.</h2>
<p>However the <span class="snippet">builder pattern will not only create objects, but prepare them for your application too.</span> The builder pattern actually <span class="snippet">uses the factory method pattern behind the scenes,</span> but I&#8217;ll get onto that soon.</p>
<p><span id="more-815"></span></p>
<h1>When to use a builder</h1>
<p>The builder pattern is most useful in large(ish) applications (like most patterns). <span class="snippet">The goal is to create an object, pre-set some of its attributes, inject dependencies and other general object setup.</span> So by the time the application (client/controller) gets the object, it&#8217;s ready to be used in its glory.</p>
<p>If you need a class which requires any kind of setup, creating a builder which will create the object for you, is almost always the better option.</p>
<h1>When not to use a builder</h1>
<p>If all you need to do initialise a class but it doesn&#8217;t require any setup, you may as well initialise the class yourself using a dependency injection container or a factory.</p>
<h1>Builders for n00bs</h1>
<p>If you were ever a junior developer, which we all were once upon a time. You will have almost definitely created a class, where you pass a bunch of attributes through to the constructor, which in turn sets up the object. This has the same end result as using a builder class but does have its drawbacks. Here are a couple of them.</p>
<ol>
<li>It can get messy quick if you start adding more than 2 or 3 arguments to you constructor. PHP Mess Detector will be on your back for sure.</li>
<li>If you need to create multiple builders for a particular class, you&#8217;ll be stuck with having to implement some disgusting switch in your constructor.</li>
<li>Testing can be harder as <span class="snippet">__construct methods cannot be stubbed.</span></li>
</ol>
<p>Saying all that, if you are absolutely sure you will only ever need 1 or 2 arguments of config and that you won&#8217;t need multiple builders. <span class="snippet">Building an object in the constructor can be tidier.</span> Just remember to <span class="snippet">never do anything but set values inside a constructor.</span></p>
<h1>Rules when using a builder</h1>
<ol>
<li>Each builder you create should have multiple methods, each method should only set one attribute, prepare one piece of config or inject one dependency.</li>
<li>Each builder you create for a class, should be polymorphic and implement the same interface.</li>
<li>Each builder should have a getResult() method, which will return the fully prepared object.</li>
<li>Instead of directing calling a builders prepare methods, the builder should be created and passed to a director object.</li>
<li>Each director object should have a build method which calls each method of the builders setup. This is possible as long as all builders implement the same interface, making them polymorphic.</li>
</ol>
<h1>Drawbacks</h1>
<p>Clutching at straws, I would say using a builder makes your code <span class="snippet">marginally harder to debug,</span> as it adds one more layer to your application.</p>
<h1>Example</h1>
<p>Please note that to keep this example slightly simpler, I have sacrificed encapsulation, by not creating setter and getter methods. Normally you would create these, but here I would rather focus on the builder class.</p>
<pre class="prettyprint linenums">
/**
 * An extremely basic class for creating people objects
 */
class Person
{
    public $employed;

    public $gender;

    const GENDER_MALE   = "Male";

    const GENDER_FEMALE = "Female";

}

/**
 * All people builder should implement this interface
 */
interface PersonBuilderInterface
{
    public function setGender();
    public function setEmployed();
    public function getResult();
}

/**
 * builder to create an employed male
 */
class EmployedMaleBuilder implements PersonBuilderInterface
{
    private $person;

    public function __construct()
    {
        $this->person = new Person();
    }

    public function setGender()
    {
        $this->person->gender = Person::GENDER_MALE;
    }

    public function setEmployed()
    {
        $this->person->employed = true;
    }

    public function getResult()
    {
        return $this->person;
    }
}

/**
 * builder to create an unemployed male
 */
class UnemployedMaleBuilder implements PersonBuilderInterface
{
    private $person;

    public function __construct()
    {
        $this->person = new Person();
    }


    public function setGender()
    {
        $this->person->gender = Person::GENDER_MALE;
    }

    public function setEmployed()
    {
        $this->person->employed = false;
    }

    public function getResult()
    {
        return $this->person;
    }
}

/**
 * builder to create an employed female
 */
class EmployedFemaleBuilder implements PersonBuilderInterface
{
    private $person;

    public function __construct()
    {
        $this->person = new Person();
    }

    public function setGender()
    {
        $this->person->gender = Person::GENDER_FEMALE;
    }

    public function setEmployed()
    {
        $this->person->employed = true;
    }

    public function getResult()
    {
        return $this->person;
    }
}

/**
 * builder to create an unemployed female
 */
class UnemployedFemaleBuilder implements PersonBuilderInterface
{
    private $person;

    public function __construct()
    {
        $this->person = new Person();
    }

    public function setGender()
    {
        $this->person->gender = Person::GENDER_FEMALE;
    }

    public function setEmployed()
    {
        $this->person->employed = false;
    }

    public function getResult()
    {
        return $this->person;
    }
}

/**
 * The director class is part of the builder patter, the build method should be passed a builder.
 * The build method should than call all of the builder methods and return a Person object
 */
class PersonDirector
{
    public function build(PersonBuilderInterface $builder)
    {
        $builder->setGender();
        $builder->setEmployed();

        return $builder->getResult();
    }
}

$director                = new PersonDirector();
$employedMaleBuilder     = new EmployedMaleBuilder();
$unemployedMaleBuilder   = new UnemployedMaleBuilder();
$employedFemaleBuilder   = new EmployedFemaleBuilder();
$unemployedFemaleBuilder = new UnemployedFemaleBuilder();

/**
 * object(Person)#3 (2) {
 * (
 *   ["employed"] => bool(true)
 *   ["gender"] => string(4) "Male"
 * )
 */
$employedMale     = $director->build($employedMaleBuilder);

/**
 * object(Person)#5 (2) {
 * (
 *   ["employed"] => bool(false)
 *   ["gender"] => string(4) "Male"
 * )
 */
$unemployedMale   = $director->build($unemployedMaleBuilder);

/**
 * object(Person)#7 (2) {
 * (
 *   ["employed"] => bool(true)
 *   ["gender"] => string(4) "Female"
 * )
 */
$employedFemale   = $director->build($employedFemaleBuilder);

/**
 * object(Person)#11 (2) {
 * (
 *   ["employed"] => bool(false)
 *   ["gender"] => string(4) "Female"
 * )
 */
$unemployedFemale = $director->build($unemployedFemaleBuilder);
</pre>
<p>The code above is all pretty simple stuff. There is just one thing I don&#8217;t like, the <span class="snippet">new</span> keyword. Creating objects by using the new keyword, should be kept to an absolute minimum, ideally objects should only be created inside service locators and factories.</p>
]]></content:encoded>
										</item>
		<item>
		<title>Factory Pattern in PHP</title>
		<link>https://www.jakowicz.com/factory-pattern-in-php/</link>
				<comments>https://www.jakowicz.com/factory-pattern-in-php/#respond</comments>
				<pubDate>Thu, 27 Mar 2014 09:16:00 +0000</pubDate>
		<dc:creator><![CDATA[Simon]]></dc:creator>
				<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[OOP]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Abstract Factory]]></category>
		<category><![CDATA[Creational Pattern]]></category>
		<category><![CDATA[Factory Method]]></category>
		<category><![CDATA[Factory Pattern]]></category>
		<category><![CDATA[Simple Factory]]></category>
		<category><![CDATA[Static Factory]]></category>

		<guid isPermaLink="false">http://www.jakowicz.com/?p=789</guid>
				<description><![CDATA[This is post 4 of 13 in the series &#8220;PHP Design Patterns&#8221; The factory pattern is one of the most commonly used design patterns, something you&#8217;ll definitely be glad to have in your toolbox. It&#8217;s also pretty simple to get to grips with and start reaping the benefits. The purpose of any factory class, is... <a class="more-link" href="https://www.jakowicz.com/factory-pattern-in-php/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
								<content:encoded><![CDATA[<aside class="wp-post-series-box series-php-design-patterns">
	<p class="wp-post-series-name">
		This is post 4 of 13 in the series <em>&ldquo;PHP Design Patterns&rdquo;</em>	</p>

	
	</aside>
<h2>The factory pattern is one of the most commonly used design patterns, something you&#8217;ll definitely be glad to have in your toolbox. It&#8217;s also pretty simple to get to grips with and start reaping the benefits.</h2>
<p><span class="snippet">The purpose of any factory class, is to create and return instances of other classes,</span> just like a real world factory creates products. There are two types of factory design patterns. One is called the <span class="snippet">factory method</span> and the other is called an <span class="snippet">abstract factory.</span> There is another not official pattern called simple factory. All are described in detail below. Let&#8217;s get going.</p>
<p><span id="more-789"></span></p>
<h2>Simple factory</h2>
<p>Simple factories, which are <span class="snippet">sometimes called static factories,</span> are the simplest form of a factory. Although it&#8217;s not an official design pattern, it does have it&#8217;s uses especially in small to mid sized applications.</p>
<p>Simple factories are classes which can <span class="snippet">return a single class (these are called product classes) instance,</span> the class to initialise could be hard coded (if the factory only returns objects of one particular product) or determined at runtime (if there are multiple classes which could be initialised), this is commonly done with a switch statement.</p>
<h3>Rules</h3>
<ol>
<li>The factory class must have a static method, this is called a factory method.</li>
<li>The factory method must return a class instance.</li>
<li>Only one object should be created and returned at a time.</li>
</ol>
<h3>Example</h3>
<pre class="prettyprint linenums">
/**
 * All animal should extend this abstract animal class
 */
abstract class AnimalAbstract 
{
    protected $species;

    public function getSpecies() {
        return $this->species;
    }
}

/**
 * used to represent a cat
 */
class Cat extends AnimalAbstract 
{
    protected $species = 'cat';
}

/**
 * used to represent a dog
 */
class Dog extends AnimalAbstract 
{
    protected $species = 'dog';
}

/**
 * The is the factory which creates animal objects
 */
class AnimalFactory 
{
    public static function factory($animal) 
    {
        switch ($animal) {
            case 'cat':
                $obj = new Cat();
                break;
            case 'dog':
                $obj = new Dog();
                break;
            default:
                throw new Exception("Animal factory could not create animal of species '" . $animal . "'", 1000);
        }
        return $obj;
    }
}

try {

    $cat = AnimalFactory::factory('cat'); // object(Cat)#1
    echo $cat->getSpecies(); // cat

    $dog = AnimalFactory::factory('dog'); // object(Dog)#1
    echo $dog->getSpecies(); // dog

    $hippo = AnimalFactory::factory('hippopotamus'); // This will throw an Exception

} catch(Exception $e) {
    echo $e->getMessage(); // AnimalFactory could not create animal of species 'hippopotamus'
}
</pre>
<h2>Factory method</h2>
<p>The factory method is close to identical to the simple factory. The only difference between them, is that instead of having a single factory, <span class="snippet">you have multiple factories.</span> This is <span class="snippet">useful if you have a large amount of product classes and want to group them.</span> An example of this would be, instead of creating an animal factory, which could return any type of animal in the world (which would obviously be massive). You would have multiple factories to group animal how you see fit, e.g. PetAnimalFactory, FarmAnimalFactory, SafariAnimalFactory etc.</p>
<h3>Rules</h3>
<ol>
<li>Each factory you create e.g. PetAnimalFactory and FarmAnimalFactory, must implement a factory interface, making them polymorphic.</li>
<li>Each product class (here these are the animals) you create must also implement an animal interface, making them polymorphic too.</li>
<li>Each factory must have a factory method which will return an animal instance.</li>
</ol>
<h3>Advantages</h3>
<ol>
<li>Hides product classes from the client/controller, which helps to remove dependencies.</li>
<li>All product classes are forced to be polymorphic and thus interchangable.</li>
</ol>
<h3>Drawbacks</h3>
<ol>
<li>Each factory, becomes a dependency of the application, these could be stored in a dependency injection container to mitigate this.</li>
</ol>
<h3>Example</h3>
<pre class="prettyprint linenums">
/**
 * All animal should extend this abstract animal class
 */
abstract class AnimalAbstract 
{
    protected $species;

    public function getSpecies() {
        return $this->species;
    }
}

/**
 * used to represent a cat
 */
class Cat extends AnimalAbstract 
{
    protected $species = 'cat';
}

/**
 * used to represent a dog
 */
class Dog extends AnimalAbstract 
{
    protected $species = 'dog';
}

/**
 * used to represent a pig
 */
class Pig extends AnimalAbstract 
{
    protected $species = 'pig';
}

/**
 * used to represent a chicken
 */
class Chicken extends AnimalAbstract 
{
    protected $species = 'chicken';
}

/**
 * used to represent a zebra
 */
class Zebra extends AnimalAbstract 
{
    protected $species = 'zebra';
}

/**
 * used to represent a giraffe
 */
class Giraffe extends AnimalAbstract 
{
    protected $species = 'giraffe';
}

/**
 * used to represent a all factories should implement this interface
 */
interface AnimalFactoryInterface 
{
    public static function factory($animal);
}

/**
 * this should be used to create all animals which are pets
 */
class PetAnimalFactory implements AnimalFactoryInterface
{
    public static function factory($animal) 
    {
        switch ($animal) {
            case 'cat':
                $obj = new Cat();
                break;
            case 'dog':
                $obj = new Dog();
                break;
            default:
                throw new Exception("Pet animal factory could not create animal of species '" . $animal . "'", 1000);
        }
        return $obj;
    }
}

/**
 * this should be used to create all animals which are farm animals
 */
class FarmAnimalFactory implements AnimalFactoryInterface 
{
    public static function factory($animal) 
    {
        switch ($animal) {
            case 'pig':
                $obj = new Pig();
                break;
            case 'chicken':
                $obj = new Chicken();
                break;
            default:
                throw new Exception("Farm animal factory could not create animal of species '" . $animal . "'", 1000);
        }
        return $obj;
    }
}

/**
 * this should be used to create all animals which are safari animals
 */
class SafariAnimalFactory implements AnimalFactoryInterface
{
    public static function factory($animal) 
    {
        switch ($animal) {
            case 'zebra':
                $obj = new Zebra();
                break;
            case 'giraffe':
                $obj = new Giraffe();
                break;
            default:
                throw new Exception("Safari animal factory could not create animal of species '" . $animal . "'", 1000);
        }
        return $obj;
    }
}

try {

    $cat = PetAnimalFactory::factory('cat'); // object(Cat)#1
    echo $cat->getSpecies(); // cat

    $pig = FarmAnimalFactory::factory('pig'); // object(Pig)#1
    echo $pig->getSpecies(); // pig

    $giraffe = SafariAnimalFactory::factory('giraffe'); // object(Giraffe)#1
    echo $giraffe->getSpecies(); // giraffe

    $petChicken = PetAnimalFactory::factory('chicken'); // This will throw an Exception

} catch(Exception $e) {
    echo $e->getMessage(); // PetAnimalFactory could not create animal of species 'chicken'
}
</pre>
<h2>Abstract factory</h2>
<p><span class="snippet">The goal here, is to create a factory (the abstract factory), which creates product factories (in the example below these are output types). The product factories then create the actual products (below these are the pretty and ugly output type classes).</span> Each product factory class has multiple methods for creating different class instances.</p>
<h3>Rules</h3>
<ol>
<li>Each product factory must extend the same abstract class or implement the same interface.</li>
<li>Each product factory must have multiple methods, one for each class it wants to initialise.</li>
<li>Each product factory class you create must have the same methods. The same methods in each factory must return polymorphic class instances and implement the same interface . If this is still unclear, the example should clear things up.</li>
</ol>
<h3>Advantages</h3>
<ol>
<li>Hides product classes from the client/controller, which helps to remove dependencies.</li>
<li>All product classes are made to be polymorphic, thus interchangable.</li>
<li>It promote consistency among products, all products should be grouped by the product factories</li>
</ol>
<h3>Drawbacks</h3>
<ol>
<li>When adding a new product class, the abstract factory would need updating, this violates the <a href="/solid-development/">Interface Segregation principle</a>. You&#8217;ll be hard pushed to find someone who actually gives a damn.</li>
</ol>
<h3>Example</h3>
<pre class="prettyprint linenums">
/**
 * This is the abstract factory, each factory should extend this (WebOutputTypeFactory & DataOutputTypeFactory)
 */
abstract class AbstractOutputTypeFactory
{
    abstract public function prettyOutput();

    abstract public function uglyOutput();
}

/**
 * All class which represent pretty output, should extend this class
 */
abstract class AbstractPrettyOutput
{
    abstract public function getPrettyOutput();
}

/**
 * All class which represent ugly output, should extend this class
 */
abstract class AbstractUglyOutput
{
    abstract public function getUglyOutput();
}

/**
 * This is a factory which can create all types of web output objects
 */
class WebOutputTypeFactory extends AbstractOutputTypeFactory
{
    public function prettyOutput()
    {
        return new WebPrettyOutput();
    }

    public function uglyOutput()
    {
        return new WebUglyOutput();
    }
}

/**
 * This is a factory which can create all types of data output objects
 */
class DataOutputTypeFactory extends AbstractOutputTypeFactory
{
    public function prettyOutput()
    {
        return new DataPrettyOutput();
    }

    public function uglyOutput()
    {
        return new DataUglyOutput();
    }
}

/**
 * This class will represent pretty web output (e.g. HTML)
 */
class WebPrettyOutput extends AbstractPrettyOutput
{
    public function getPrettyOutput()
    {
        return '&lt;h1&gt;Imagine you had some really pretty web output here&lt;/h1&gt;';
    }
}

/**
 * This class will represent ugly web output (e.g. XML)
 */
class WebUglyOutput extends AbstractUglyOutput
{
    public function getUglyOutput()
    {
        return '<data name="SuperUglyyyyMess">Imagine you had some really ugly web output here</data>';
    }
}

/**
 * This class will represent pretty data output (e.g. JSON)
 */
class DataPrettyOutput extends AbstractPrettyOutput
{
    public function getPrettyOutput()
    {
        return "{ 'text': 'Imagine you had some really pretty data output here' }";
    }
}

/**
 * This class will represent ugly data output(e.g. CSV)
 */
class DataUglyOutput extends AbstractUglyOutput
{
    public function getUglyOutput()
    {
        return 'Imagine, you, had, some, really, ugly, CSV, output, here';
    }
}

// this is used to create web outputs
$webFactory = new WebOutputTypeFactory();

$webPretty = $webFactory->prettyOutput();
echo $webPretty->getPrettyOutput(); // <h1>Imagine you had some really pretty web output here</h1>

$webUgly = $webFactory->uglyOutput();
echo $webUgly->getUglyOutput(); // <data name="SuperUglyyyyMess">Imagine you had some really ugly web output here</data>

// this is used to create data outputs
$dataFactory = new DataOutputTypeFactory();

$dataPretty = $dataFactory->prettyOutput();
echo $dataPretty->getPrettyOutput(); // { 'text': 'Imagine you had some really pretty data output here' }

$dataUgly = $dataFactory->uglyOutput();
echo $dataUgly->getUglyOutput(); // Imagine, you, had, some, really, ugly, CSV, output, here
</pre>
<h2>Conclusion</h2>
<p>The factory pattern is a powerful design pattern in all of its forms. Some people may tell you the simple factory shouldn&#8217;t be used, generally having poor reasons not to do so. At the end of the day we just want to get things done and unless you&#8217;re working with someone extremely anal, nobody should have a problem.</p>
<p><span class="snippet">The abstract factory pattern is by far the hardest to understand out of the three.</span> It&#8217;s not always obvious when a good time to use it would be. Don&#8217;t force this, there is a huge amount of abstraction in place which is only required when building complex systems. As long as you know what an abstract factory is, sooner or later you&#8217;ll find a genuine use case.</p>
<p>Thanks for reading</p>
<p>Until next time!</p>
]]></content:encoded>
							<wfw:commentRss>https://www.jakowicz.com/factory-pattern-in-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
							</item>
		<item>
		<title>Multitons in PHP</title>
		<link>https://www.jakowicz.com/multitons-in-php/</link>
				<comments>https://www.jakowicz.com/multitons-in-php/#comments</comments>
				<pubDate>Fri, 21 Mar 2014 09:03:00 +0000</pubDate>
		<dc:creator><![CDATA[Simon]]></dc:creator>
				<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[OOP]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Creational Pattern]]></category>
		<category><![CDATA[multiton]]></category>
		<category><![CDATA[singleton]]></category>

		<guid isPermaLink="false">http://www.jakowicz.com/?p=729</guid>
				<description><![CDATA[This is post 3 of 13 in the series &#8220;PHP Design Patterns&#8221; In my last blog I covered the singleton design pattern (DP), showing how and when to use it. In this article I am going to cover a very similar design pattern called the multiton. A multiton is almost exactly the same as a... <a class="more-link" href="https://www.jakowicz.com/multitons-in-php/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
								<content:encoded><![CDATA[<aside class="wp-post-series-box series-php-design-patterns">
	<p class="wp-post-series-name">
		This is post 3 of 13 in the series <em>&ldquo;PHP Design Patterns&rdquo;</em>	</p>

	
	</aside>
<h2>In my last blog I covered the singleton design pattern (DP), showing how and when to use it. In this article I am going to cover a very similar design pattern called the multiton.</h2>
<p><span class="snippet">A multiton is almost exactly the same as a singleton, the one slight difference is a multiton can store multiple instances of itself.</span> Contrary to a singleton, which can only store one instance of itself.</p>
<p><span id="more-729"></span></p>
<h2>When to use a multiton</h2>
<p>The ideal use for a multiton is when you need to create multiple instances of a particular class and you want to store references to each instance. This is most useful when you&#8217;re only creating a small amount of the class in question and you want to access different instances in different parts of your code. I&#8217;m going to use a database example again, solely because it&#8217;s the best real world use case. If you start creating more than 5-10 instance of a multiton, than you probably shouldn&#8217;t be using a multiton and rather storing the objects in a dependency injection container (DIC). <span class="snippet">Multitons are only for creating a small collection of objects.</span></p>
<h2>Rules when creating a multiton</h2>
<ol>
<li>Just like a singleton, <span class="snippet">multitons should have a private __construct() method.</span> Instances should be created using a static getInstance() method.</li>
<li>Each instance of the multiton which is created should be stored inside a static $instances attribute</li>
<li>When the getInstance() method is called a value should be passed as the only argument, this value should be used as the key when storing the instance inside the $instances attribute.</li>
<li>To retrieve an existing instance, the name of the instance you want to retrieve should be passed to the getInstance() method, which will return the pre-initialised instance, instead of creating a new instance.</li>
</ol>
<h2>Drawbacks</h2>
<p>For full details on the drawback you should check out the article I wrote on <a href="singletons-in-php">singletons</a>, as they have the same problems. But here is a quick summary.</p>
<ol>
<li>Multitons add dependencies to your code because the are called globally.</li>
<li>They are <span class="snippet">hard to test</span> because of their use of static methods and attributes.</li>
</ol>
<h2>Code Example</h2>
<pre class="prettyprint linenums">
class Database {

    /**
     * Used to store and provide instances for the getInstance() method
     */ 
    private static $instances = array();

    /**
     * Hidden constructor, only callable from within this class
     */
    private function __construct() { }

    /**
     * Create a new instance if one doesn't exist with the key provided.
     * Once an instance has been created, or if it was already created, return it.
     * @param $key the key which the instance should be stored/retrieved
     * @return self
     */
    public static function getInstance($key) {

        // Check if an instance exists with this key already
        if(!array_key_exists($key, self::$instances)) {
            // instance doesn't exist yet, so create it
            self::$instances[$key] = new self();
        }

        // Return the correct instance of this class
        return self::$instances[$key];
    }

    /**
     * Hidden magic clone method, make sure no instances of this class 
     * can be cloned using the clone keyword
     */
    private function __clone() { }
    
}

// Create first instance to the master database
$master = Database::getInstance('master');
var_dump($master); // object(Database)#1 (0) { }

// Create second instance of this class for a logger database
$logger = Database::getInstance('logger');
var_dump($logger); // object(Database)#2 (0) { }

// Retrieve the existing 'master' instance from the multiton
// this would normally be done in script, which doesn't have the instance already
$masterDupe = Database::getInstance('master');
var_dump($masterDupe); // object(Database)#1 (0) { }

// Database objects cannot be initialise with the new keyword, doing so will cause fatal errors
// Fatal error: Call to private Database::__construct() from invalid context
$dbFatalError = new Database();

// Database objects cannot be cloned, doing so will cause a fatal error
// PHP Fatal error:  Call to private Database::__clone()
$dbCloneError = clone $masterDupe;
</pre>
]]></content:encoded>
							<wfw:commentRss>https://www.jakowicz.com/multitons-in-php/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
							</item>
		<item>
		<title>Singletons in PHP</title>
		<link>https://www.jakowicz.com/singletons-in-php/</link>
				<comments>https://www.jakowicz.com/singletons-in-php/#respond</comments>
				<pubDate>Tue, 25 Feb 2014 00:11:31 +0000</pubDate>
		<dc:creator><![CDATA[Simon]]></dc:creator>
				<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[OOP]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Creational Pattern]]></category>
		<category><![CDATA[singleton]]></category>

		<guid isPermaLink="false">http://jakowicz.com/?p=711</guid>
				<description><![CDATA[This is post 2 of 13 in the series &#8220;PHP Design Patterns&#8221; If you&#8217;ve heard of design patterns you&#8217;ll have probably heard of the singleton pattern. It&#8217;s debatably the easiest to start with and get you on the road to becoming the Walter White of design patterns. Below I will explain what a singleton is,... <a class="more-link" href="https://www.jakowicz.com/singletons-in-php/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
								<content:encoded><![CDATA[<aside class="wp-post-series-box series-php-design-patterns">
	<p class="wp-post-series-name">
		This is post 2 of 13 in the series <em>&ldquo;PHP Design Patterns&rdquo;</em>	</p>

	
	</aside>
<h2>If you&#8217;ve heard of design patterns you&#8217;ll have probably heard of the singleton pattern. It&#8217;s debatably the easiest to start with and get you on the road to becoming the Walter White of design patterns. Below I will explain what a singleton is, when you should use a singleton, rules that must be followed, drawbacks and I will provide sample code. Lets get started.</h2>
<h2>What is a singleton</h2>
<p>As the name sort of implies, a <span class="snippet">singleton is a class that can only be initialised once per request to an application.</span> E.g once per HTTP request on a website.</p>
<p><span id="more-711"></span></p>
<h2>When to use a singleton</h2>
<p>The ideal use for a singleton is when you only need one instance of a particular class in your application. The most common use for this in small to mid sized application is probably for creating a database connection. In such an application it would be very rare that you would need to connect to two separate databases. You would also want to make sure that it&#8217;s not possible to open multiple connections to the same database, because this would be inefficient.</p>
<h2>Rules when creating a singleton</h2>
<ol>
<li>As a singleton should only be initialised once, you have to prevent multiple instantiations, this is done my <span class="snippet">making the _construct() method private,</span> this will stop the singleton class from being initialised with the new keyword.</li>
<li>Initialising must be done by creating a public static method (typically called getInstance() or singleton()) which you can use to create an instance of itself.</li>
<li>When an instance is created of itself, that <span class="snippet">instance must be stored inside a static attribute.</span></li>
<li>On the second call to the static method instead of creating an instance to itself again, it will return the object it created the first time around. This way the class can only be initialised once.</li>
<li>Lastly the Singleton <span class="snippet">must have a private _clone() method</span> to prevent one instance of the Singleton being cloned using the PHP clone keyword.</li>
</ol>
<h2>Drawbacks</h2>
<ol>
<li>Typically singletons are used in the global state, which means they are called within other classes (e.g. via ClassName::getInstance()), this <span class="snippet">adds dependencies to your system.</span> This can be countered by passing around the singleton instance, however it does not follow the pattern goals.</li>
<li>Singletons are extremely hard to test because <span class="snippet">static methods cannot be stubbed</span> and a static method is used to initialise and retrieve the class instance. Last year I wrote an article on <a href="/phpunit-testing-singleton-dependencies/">testing singleton dependencies</a>.</li>
<li>Singletons violate the single responsibility principle by controlling their own life cycle, i.e they create themselves.< \li>
</li>
</ol>
<h2>Code Example</h2>
<pre class="prettyprint linenums">
class Database {

    /**
     * Used to store and provide instance for the getInstance() method
     */ 
    private static $instance;

    /**
     * Hidden constructor, only callable from within this class
     */
    private function __construct() { }

    /**
     * Create an instance if it hasn't been already
     * Then return the instance of this class
     * @return self
     */
    public static function getInstance() {

        if(!self::$instance) {
            // instance doesn't exist yet, so create it
            self::$instance = new self();
        }

        // return an instance of this class (Database)
        return self::$instance;
    }

    /**
     * Hidden magic clone method, make sure an instance this class 
     * cannot be cloned using the clone keyword
     */
    private function __clone() { }
    
}

// Making two calls to Database::getInstance(); return the same object
$db = Database::getInstance();
var_dump($db); // object(Database)#1 (0) { }

$db2 = Database::getInstance();
var_dump($db2); // object(Database)#1 (0) { }

// Database cannot be initialise with the new keyword and will create a fatal error
// Fatal error: Call to private Database::__construct() from invalid context 
// in singleton.php on line 44
$db_fatal_error = new Database();
</pre>
]]></content:encoded>
							<wfw:commentRss>https://www.jakowicz.com/singletons-in-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
							</item>
	</channel>
</rss>
