<?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>OOP &#8211; Simon Jakowicz</title>
	<atom:link href="https://www.jakowicz.com/tag/oop/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>Proxy pattern in PHP</title>
		<link>https://www.jakowicz.com/proxy-pattern-in-php/</link>
				<comments>https://www.jakowicz.com/proxy-pattern-in-php/#comments</comments>
				<pubDate>Thu, 10 Jul 2014 20:04:18 +0000</pubDate>
		<dc:creator><![CDATA[Simon]]></dc:creator>
				<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[OOP]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Proxy Pattern]]></category>
		<category><![CDATA[Structural Pattern]]></category>

		<guid isPermaLink="false">http://www.jakowicz.com/?p=984</guid>
				<description><![CDATA[This is post 13 of 13 in the series &#8220;PHP Design Patterns&#8221; The next structural design pattern in this series is called the proxy pattern. You can think of these, just like any other proxy. The aim here is to create a class which takes full responsibility for the execution of another class. Yup you... <a class="more-link" href="https://www.jakowicz.com/proxy-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 13 of 13 in the series <em>&ldquo;PHP Design Patterns&rdquo;</em>	</p>

	
	</aside>
<h2>The next structural design pattern in this series is called the proxy pattern. You can think of these, just like any other proxy. The aim here is to create a class which takes full responsibility for the execution of another class.</h2>
<p>Yup you got it&#8230; technically they are wrappers as well, however they aren&#8217;t labelled this way.</p>
<p><span id="more-984"></span></p>
<h2>What is the proxy pattern</h2>
<p>The proxy pattern is a way of creating an <span class="snippet">intermediary between your client/controller and your subject class.</span> Think of a HTTP proxy, which is a gateway between your browser (client) and a server (subject). These proxies can be used to enhance a user experience by caching data, removing adverts, allowing access to restricted content <img src="https://s.w.org/images/core/emoji/11.2.0/72x72/1f61b.png" alt="😛" class="wp-smiley" style="height: 1em; max-height: 1em;" /> plus much more. The proxy pattern has the similar goals and so <span class="snippet">can be used to simplify, optimise and enhance existing subjects (classes).</span></p>
<h2>When to use the proxy pattern</h2>
<p>I stated above that the proxy pattern can simplify, optimise and enhance existing subjects. This is completely true, but I want to focus on optimisation. If the main goal of your new class is to simplify or enhance, you may be better off using a facade or a decorator respectively. Saying that&#8230;. simplifications and enhancements are good additions to a proxy focusing on optimisation.</p>
<p><span class="snippet">One of the main optimisation use cases for the proxy pattern is lazy initialisation of your subject.</span> What this means is, instead of initialising your subject in the client. The client would initialise the proxy and the proxy would only initialise the subject when required. This is most useful when your subject initialisation does a large amount of setup that potentially the client will never need.</p>
<h2>Rules</h2>
<ol>
<li>The subject class and the proxy class should implement the same interface.</li>
</ol>
<h2>Advantages</h2>
<ol>
<li>Using proxies can optimise your application by only loading resources which are required.</li>
<li>Using a proxy class can make your implementation cleaner and easier to maintain.</li>
</ol>
<h2>Example</h2>
<pre class="prettyprint linenums">
abstract class ReadFileAbstract
{
    protected $fileName;
    protected $contents;

    public function getFileName()
    {
        return $this->fileName;
    }

    public function setFileName($fileName)
    {
        $this->fileName = $fileName;
    }

    public function getContents()
    {
        return $this->contents;
    }
}

class ReadFile extends ReadFileAbstract
{
    const DOCUMENTS_PATH = "/home/simon";

    public function __construct($fileName)
    {
        $this->setFileName($fileName);
        $this->contents = file_get_contents(self::DOCUMENTS_PATH . "/" . $this->fileName);
    }
}

class ReadFileProxy extends ReadFileAbstract
{
    private $file;

    public function __construct($fileName)
    {
        $this->fileName = $fileName;
    }

    public function lazyLoad()
    {
        if ($this->file === null) {
            $this->file = new ReadFile($this->fileName);
        }
        return $this->file;
    }
}

$proxies = array();

for ($i = 0; $i < 10; $i++) {
    // tell the proxy which file should be read (when lazy loaded)
    $proxies[$i] = new ReadFileProxy("file" . $i . ".txt");
}

// Now it's time to read the contents of file3.txt
$file3 = $proxies[3]->lazyLoad();

// echo the contents of file3.txt
echo $file3->getContents();
</pre>
<h2>What just happened here</h2>
<p>As described above, one of the proxy pattern use cases is to lazy load resources. In this case, it&#8217;s the file contents which are being lazy loaded. Inside the for loop, 10 instances to the ReadFileProxy class are created, however the file content of file 3, is only read on a call to the lazyLoad() method. This means the 9 other proxy objects that were created, didn&#8217;t need to perform slow read operations on the file system.</p>
]]></content:encoded>
							<wfw:commentRss>https://www.jakowicz.com/proxy-pattern-in-php/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
							</item>
		<item>
		<title>Bridge pattern in PHP</title>
		<link>https://www.jakowicz.com/bridge-pattern-in-php/</link>
				<comments>https://www.jakowicz.com/bridge-pattern-in-php/#comments</comments>
				<pubDate>Sat, 05 Jul 2014 10:57:40 +0000</pubDate>
		<dc:creator><![CDATA[Simon]]></dc:creator>
				<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[OOP]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Bridge Pattern]]></category>
		<category><![CDATA[Structural Pattern]]></category>

		<guid isPermaLink="false">http://www.jakowicz.com/?p=980</guid>
				<description><![CDATA[This is post 12 of 13 in the series &#8220;PHP Design Patterns&#8221; The bridge pattern is another structural design pattern. The design pattern states that the bridge pattern should decouple an abstraction from its implementation. That sounds a lot one of the main goals of OOP, programming to an interface using polymorphism and abstraction to... <a class="more-link" href="https://www.jakowicz.com/bridge-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 12 of 13 in the series <em>&ldquo;PHP Design Patterns&rdquo;</em>	</p>

	
	</aside>
<h2>The bridge pattern is another structural design pattern. The design pattern states that the bridge pattern should decouple an abstraction from its implementation. That sounds a lot one of the main goals of OOP, programming to an interface using polymorphism and abstraction to achieve inversion of control.</h2>
<p>As much as that&#8217;s what it sounds like, that&#8217;s not the goal of the bridge pattern, it&#8217;s more the means of achieving the goal. I like to think of the bridge pattern as a multi-dimensional strategy pattern. I&#8217;ve not covered the strategy pattern yet but you can think of it as providing an interface to build multiple strategies or algorithms which can be selected at run time.</p>
<p>The bridge pattern differs from this, in that you build two collections of strategies, where all strategies from one interface can make use of the strategies from the other interface. As an example lets assume you have a device strategy with 3 implementations (Phone, Tablet &#038; Laptop), you also have 3 messaging strategies (Skype, WhatsApp, Facebook). The goal is to build an application where every device can interchangeably use every messaging platform using composition.</p>
<p><span id="more-980"></span></p>
<h2>Why would you use the bridge pattern</h2>
<p>The build pattern helps to reduce the number of classes required and prevents repetition of code between classes, keeping your code DRY. Also just like in the strategy pattern it allows you to change to functionality of you application at run time.</p>
<h2>Example</h2>
<pre class="prettyprint linenums">
interface DeviceInterface { 
    public function setSender(MessagingInterface $sender);
 
    public function send($body);
}

abstract class Device implements DeviceInterface {
    protected $sender;

    public function setSender(MessagingInterface $sender) {
        $this->sender = $sender;
    }
}

class Phone extends Device {
    public function send($body) {
        $body .= "\n\n Sent from a phone.";

        return $this->sender->send($body);
    }
}

class Tablet extends Device {
    public function send($body) {
        $body .= "\n\n Sent from a Tablet.";

        return $this->sender->send($body);
    }
}

interface MessagingInterface { 
    public function send($body);
}

class Skype implements MessagingInterface {
    public function send($body) {
        // Send a message through the Skype API
    }
}

class Whatsapp implements MessagingInterface {
    public function send($body) {
        // Send a message through the Whatsapp API
    }
}

$phone = new Phone;
$phone->setSender(new Skype);

$phone->send("Hey Buddy");
</pre>
<h2>Conclusion</h2>
<p>As we can see from the above example we have a collection of devices which all implement the same interface and we have a collection of messaging services which all implement the same interface. When building a device object, we must provide it with a messaging object, allowing us to send messages through that services API.</p>
]]></content:encoded>
							<wfw:commentRss>https://www.jakowicz.com/bridge-pattern-in-php/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
							</item>
		<item>
		<title>Composite Pattern in PHP</title>
		<link>https://www.jakowicz.com/composite-pattern-in-php/</link>
				<comments>https://www.jakowicz.com/composite-pattern-in-php/#comments</comments>
				<pubDate>Sat, 14 Jun 2014 21:25:49 +0000</pubDate>
		<dc:creator><![CDATA[Simon]]></dc:creator>
				<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[OOP]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Structural Pattern]]></category>

		<guid isPermaLink="false">http://www.jakowicz.com/?p=1686</guid>
				<description><![CDATA[This is post 11 of 13 in the series &#8220;PHP Design Patterns&#8221; Previously I covered all of the creational patterns which are useful with PHP and the majority of structural patterns. One structural pattern I never covered was the Composite pattern and so that&#8217;s what I&#8217;m covering today. The purpose of this pattern is to... <a class="more-link" href="https://www.jakowicz.com/composite-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 11 of 13 in the series <em>&ldquo;PHP Design Patterns&rdquo;</em>	</p>

	
	</aside>
<h2>Previously I covered all of the creational patterns which are useful with PHP and the majority of structural patterns. One structural pattern I never covered was the Composite pattern and so that&#8217;s what I&#8217;m covering today. The purpose of this pattern is to allow trees of objects (composites) to be handled interchangeably, regardless of if the node is a branch of a leaf node. What branch and leaf nodes are is revealed below.</h2>
<p>Let&#8217;s use a hard drive as an example, you have directories which you can think of as branches, and you have files, you can think of these as leaf nodes. Branches contain leaves just like directories contain files. Directories and files are both separate entities, but the goal of the composite pattern has them interchangeable, as always this means they should implement the same interface. Example methods that they both share include updating the owner and group, changing permissions, fetching size, created date or last modified date, etc.</p>
<p><span id="more-1686"></span></p>
<h3>Components of the Composite pattern</h3>
<ol>
<li>Component &#8211; This is the interface for your composite and entity, it represents the contract that both your branch and leaf nodes must implement.</li>
<li>Composite &#8211; The composite is a collection, each item in the collection could be another composite or a leaf node. Composites typically loop over and delegate responsibility to their composites and leaf nodes. Composites must implement the component interface.</li>
<li>Leaf Nodes &#8211; These are the individual entities, they represent the end of a tree path, meaning they have no other leaf nodes below them. These must also implement the component interface.</li>
<li>Client &#8211; The client/controller is what creates instances to the composite and leaf nodes to generate some output.</li>
</ol>
<h3>When should the composite pattern be used</h3>
<p>The ideal use case is when you have a collection of composites and entities that have a similar interface. By using the composite pattern you allow the higher level objects to delegate their work to the lower level leaf nodes using a consistent interface.</p>
<h3>Rules</h3>
<ol>
<li>Your leaf nodes and composites must implement the same component interface.</li>
<li>Your composite classes must have methods to both add and remove leaf nodes.</li>
</ol>
<h3>Advantages</h3>
<ol>
<li>The client code is kept simple, it doesn’t need to worry if it’s dealing with an individual objects or a collection.</li>
<li>Leaf nodes can be created and handled directly or via the the composite objects.</li>
</ol>
<h3>Drawbacks</h3>
<p>As both the composites and leaf nodes implement the same interface, you will likely have method signatures in your component, which you do not need in either the composite or leaf nodes. This can be countered by returning false on methods which are not required, this would, however, violate the interface segregation principle.</p>
<h3>Safety vs Transparency</h3>
<p>When implementing the composite pattern, you can either take the safe or the transparent approach. Taking the safe approach means to prevent the add and remove methods from being available in the leaf nodes. This is safe because the leaf nodes do not need these methods and so they cannot be inappropriately called, but it also means the composite and leaf nodes are no longer transparent because they have slightly different interfaces. Conversely, the transparent approach means both the composite and leaf nodes implement exactly the same interface, meaning methods will be available on the leaf nodes which are not required, this also breaks the interface segregation principle.</p>
<p>The approach you take is entirely up to you and you really be taken on a case by case basis, however, in PHP the transparent approach is generally more common.</p>
<h3>Example</h3>
<pre class="prettyprint linenums">
abstract class ComponentInterface
{
    public $id;
    public $name;

    abstract public function getFile($offset = 0);
    abstract public function addFile(ComponentInterface $file);
    abstract public function removeFile(ComponentInterface $file);

    public function __construct($id, $name)
    {
        $this->id = $id;
        $this->name = $name;
    }
}

class DirectoryComponent extends ComponentInterface
{
    private $files = [];

    public function getFile($offset = 0)
    {
        $content = str_repeat("-", $offset) . ' ' . $this->name . "/\n";

        foreach ($this->files as $file) {
            $content .= $file->getFile(++$offset);
        }

        return $content;
    }
 
    public function addFile(ComponentInterface $file)
    {
        $this->files[$file->id] = $file;

        return $this;
    }

    public function removeFile(ComponentInterface $file)
    {
        unset($this->files[$file->id]);
    }
}

class FileComponent extends ComponentInterface
{
    public function getFile($offset = 0)
    {
        return str_repeat("-", $offset-1) . '> ' . $this->name . "\n";
    }

    public function addFile(ComponentInterface $file)
    {
        return false;
    }

    public function removeFile(ComponentInterface $file)
    {
        return false;
    }
}

$root = new DirectoryComponent(1, "/");

$etc = new DirectoryComponent(2, "etc");
$var = new DirectoryComponent(3, "var");

$root->addFile($etc)->addFile($var);

$etc->addFile(
    new FileComponent(2, "php.ini", "simon")
);
$var->addFile(
    new FileComponent(3, "nginx.log", "simon")
);
$var->addFile(
    new FileComponent(3, "hadoop.log", "simon")
);

echo $root->getFile();

</pre>
<h3>Output</h3>
<p>/<br />
&#8211; etc<br />
-> php.ini<br />
&#8211; var<br />
-> nginx.log<br />
-> hadoop.log</p>
]]></content:encoded>
							<wfw:commentRss>https://www.jakowicz.com/composite-pattern-in-php/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
							</item>
		<item>
		<title>Flyweight pattern in PHP</title>
		<link>https://www.jakowicz.com/flyweight-pattern-in-php/</link>
				<comments>https://www.jakowicz.com/flyweight-pattern-in-php/#respond</comments>
				<pubDate>Wed, 11 Jun 2014 20:29:49 +0000</pubDate>
		<dc:creator><![CDATA[Simon]]></dc:creator>
				<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[OOP]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Flyweight Pattern]]></category>
		<category><![CDATA[Structural Pattern]]></category>

		<guid isPermaLink="false">http://www.jakowicz.com/?p=965</guid>
				<description><![CDATA[This is post 10 of 13 in the series &#8220;PHP Design Patterns&#8221; The flyweight pattern is todays structural pattern of the day. Put simply, the flyweight pattern is used for breaking down a large domain model into a smaller domain model and a collection of tiny object-value classes called flyweights. Flyweights can be useful when... <a class="more-link" href="https://www.jakowicz.com/flyweight-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 10 of 13 in the series <em>&ldquo;PHP Design Patterns&rdquo;</em>	</p>

	
	</aside>
<h2>The flyweight pattern is todays structural pattern of the day. Put simply, the flyweight pattern is used for breaking down a large domain model into a smaller domain model and a collection of tiny object-value classes called flyweights.</h2>
<p>Flyweights can be useful when you have a collection of objects, that contain repetitive attributes and you want to share these attributes, the end goal being to save on memory usage.</p>
<p><span id="more-965"></span></p>
<h2>Useful note, before you go any further</h2>
<p>Flyweight is extremely uncommon in the PHP ecosystem, the benefits that it provides are much more useful in game development, due to the huge amount of objects required. Regardless, below I&#8217;ve going to be covering a game implementation which you&#8217;re much more likely to find in a language like Java or C++.</p>
<h2>What is the flyweight pattern</h2>
<p>Flyweights are used for <span class="snippet">storing common and repetitive data required by models.</span> These values could be stored in each individual model&#8230; however by using flyweights, you can save memory, as instead of storing the same data everywhere, you just pass around an instance of a flyweight, which internally points to the same chunk of memory.</p>
<p><span class="snippet">Flyweight objects should be shared between models</span>, allowing a much smaller amounts of objects to be created, preventing unnecessary memory usage. Sharing objects is done slightly different to how the prototype pattern clones objects. Instead <span class="snippet">a multiton should be used which creates flyweight objects and stores references to them internally.</span> Then the second time they are requested, the object in memory is returned.</p>
<h2>When to use the flyweight pattern</h2>
<p>In PHP there generally aren&#8217;t scenarios when large numbers of sharable objects are required. As I mentioned above, the flyweight pattern is much more prominent in the game development and so the example I provide below, will focus on a PHP game implementation.</p>
<h2>Rules</h2>
<ol>
<li>Flyweight objects should never be created by the client, using the new keyword. Instances should always be created by using a factory class.</li>
<li>The factory class should store instances of each flyweight, similar to how a multiton stores references to objects in a static attribute.</li>
<li>Flyweight attributes which are not sharable (extrinsic) between all instances of the flyweight, should be supplied by the client and stored inside the flyweight object.</li>
<li>Flyweight attributes which are sharable (intrinsic), should be immutable and set into the flyweight by default.</li>
<li>The client/controller is responsible for creating the flyweights using the factory class and providing them to the domains models.</li>
</ol>
<h2>Advantages</h2>
<ol>
<li>Effective use of the flyweight pattern can provide <span class="snippet">memory consumption benefits.</span></li>
</ol>
<h2>Example</h2>
<pre class="prettyprint linenums">
interface WeaponInterface
{
    public function __construct();
    public function getBaseDamage();
    public function getEnhancementsDamage();
    public function getDamage();
    public function reload();
    public function addEnhancement(WeaponFlyweightInterface $enhancement);
}

class PlasmaRifle implements WeaponInterface
{
    
    const TOTAL_AMMO_IN_PLAMA_SHELL = 10;
    const MIN_DAMAGE = 50;
    const MAX_DAMAGE = 75;

    private $ammoRemaining = null;
    private $enhancements  = [];

    public function __construct()
    {
        $this->reload();
    }

    public function getBaseDamage()
    {
        return rand(self::MIN_DAMAGE, self::MAX_DAMAGE);
    }

    public function getEnhancementsDamage()
    {
        $damage = 0;
        foreach($this->enhancements as $enhancement) {
            $damage += $enhancement->getDamage();
        }
        return $damage;
    }

    public function getDamage()
    {
        return  $this->getBaseDamage() + $this->getEnhancementsDamage();

    }

    public function reload()
    {
        $this->ammoRemaining = self::TOTAL_AMMO_IN_PLAMA_SHELL;
    }
        
    public function addEnhancement(WeaponFlyweightInterface $enhancement)
    {
        $this->enhancements[] = $enhancement;
    }

}

interface WeaponFlyweightInterface
{
    public function getDamage();
}

class PlasmaRifleGrenadeLauncherFlyweight implements WeaponFlyweightInterface
{
    const MIN_DAMAGE = 100;
    const MAX_DAMAGE = 120;

    public function getDamage()
    {
        return rand(self::MIN_DAMAGE, self::MAX_DAMAGE);
    }
}

class PlasmaRifleExplosionFlyweight implements WeaponFlyweightInterface
{
    const MIN_DAMAGE = 500;
    const MAX_DAMAGE = 1000;

    public function getDamage()
    {
        return rand(self::MIN_DAMAGE, self::MAX_DAMAGE);
    }
}

class PlasmaRifleFlyweightFactory
{
    private static $instances = [];

    public static function factory($flyweight)
    {
        $className = "PlasmaRifle" . $flyweight . "Flyweight";

        if(empty(self::$instances[$className])) {
            self::$instances[$className] = new $className();
        }
        return self::$instances[$className];
    }
}

$plasmaRifle = new PlasmaRifle();

$plasmaRifle->addEnhancement(PlasmaRifleFlyweightFactory::factory("GrenadeLauncher"));
$plasmaRifle->addEnhancement(PlasmaRifleFlyweightFactory::factory("GrenadeLauncher"));
$plasmaRifle->addEnhancement(PlasmaRifleFlyweightFactory::factory("GrenadeLauncher"));
$plasmaRifle->addEnhancement(PlasmaRifleFlyweightFactory::factory("GrenadeLauncher"));
$plasmaRifle->addEnhancement(PlasmaRifleFlyweightFactory::factory("GrenadeLauncher"));

$plasmaRifle->addEnhancement(PlasmaRifleFlyweightFactory::factory("Explosion"));
$plasmaRifle->addEnhancement(PlasmaRifleFlyweightFactory::factory("Explosion"));
$plasmaRifle->addEnhancement(PlasmaRifleFlyweightFactory::factory("Explosion"));
$plasmaRifle->addEnhancement(PlasmaRifleFlyweightFactory::factory("Explosion"));
$plasmaRifle->addEnhancement(PlasmaRifleFlyweightFactory::factory("Explosion"));

// Shot damage can vary wildly due to the random factor in base damage and flyweight enhancements
echo "Shot 1 Damage: " . $plasmaRifle->getDamage(); # Shot 1 Damage: 3944
echo "Shot 2 Damage: " . $plasmaRifle->getDamage(); # Shot 2 Damage: 4637
echo "Shot 3 Damage: " . $plasmaRifle->getDamage(); # Shot 3 Damage: 4345
</pre>
]]></content:encoded>
							<wfw:commentRss>https://www.jakowicz.com/flyweight-pattern-in-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
							</item>
		<item>
		<title>Facade pattern in PHP</title>
		<link>https://www.jakowicz.com/facade-pattern-in-php/</link>
				<comments>https://www.jakowicz.com/facade-pattern-in-php/#comments</comments>
				<pubDate>Wed, 28 May 2014 23:03:17 +0000</pubDate>
		<dc:creator><![CDATA[Simon]]></dc:creator>
				<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[OOP]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Facade Pattern]]></category>
		<category><![CDATA[Structural Pattern]]></category>

		<guid isPermaLink="false">http://www.jakowicz.com/?p=926</guid>
				<description><![CDATA[This is post 9 of 13 in the series &#8220;PHP Design Patterns&#8221; The facade pattern is today&#8217;s structural design pattern. My previous two blogs were about the adapter and the decorator patterns and just like these pattern, the facade pattern is also a known as a wrapper. The facade pattern does have some similarities to... <a class="more-link" href="https://www.jakowicz.com/facade-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 9 of 13 in the series <em>&ldquo;PHP Design Patterns&rdquo;</em>	</p>

	
	</aside>
<h2>The facade pattern is today&#8217;s structural design pattern. My previous two blogs were about the adapter and the decorator patterns and just like these pattern, the facade pattern is also a known as a wrapper.</h2>
<p>The facade pattern does have some similarities to the adapter pattern, in that they’re both used to modify the interface of an entity. However the decorator pattern is used in a very different manner. In case you forgot, here is a quick run down.</p>
<table class="blog-table">
<tr>
<th>Pattern</th>
<th>Purpose</th>
</tr>
<tr>
<td>Adapter</td>
<td>Used to allow incompatible interfaces to work together.</td>
</tr>
<tr>
<td>Decorator</td>
<td>Allows behaviours to be added to an object, without modifying the original class.</td>
</tr>
<tr>
<td>Facade</td>
<td>Provides a simplified interface to a more complex library.</td>
</tr>
</table>
<p><span id="more-926"></span></p>
<h2>What is the facade pattern</h2>
<p>The purpose of a facade in development and the real world, is to mask something ugly with something attractive. Taking this information, <span class="snippet">the facade pattern, is a means of converting the ugly interface of one or more classes into a pretty interface,</span> that you will love to work with (hopefully). This is frequently described as <span class="snippet">creating a unified interface to a sub system or multiple sub systems.</span></p>
<h2>When to use the facade pattern</h2>
<p>The facades patterns ideal use case is when you have legacy code to work with, or when you are working with a 3rd party code. As is usually the case, the code is usually impossible to re-factor as there are no tests. Instead you should create a facade (wrapper) around the original classes to simplify their usage.</p>
<h2>When to use a facade and when to use a builder</h2>
<p>Facades and builders can sound very similar, they are both used to simplify the usage of a class. However that is where their similarities end.</p>
<ol>
<li>Builder &#8211; These are specific to when initialising a class is long winded. <span class="snippet">Builders are used to initialise and prepare the objects.</span></li>
<li>Facade &#8211; These can be used to achieve what a builder does, however they are much more <span class="snippet">aimed at simplifying an interface.</span> This primarily means, renaming methods, merging methods and providing default parameters to methods.</li>
</ol>
<h2>How to use the facade pattern</h2>
<ol>
<li>Create a wrapper class, this is the facade.</li>
<li>Pass the original ugly class instances to the facade.</li>
<li>Use the facade to abstract away the entire sub system and produce a new beautiful API.</li>
</ol>
<h2>Rules</h2>
<ol>
<li>The sub system (this is the ugly object) should not be stored as a static attribute inside the facade. This would result in <span class="snippet">antichrist global state issues.</span> This is due to how PHP shares static attributes between objects.</li>
</ol>
<h2>Advantages</h2>
<ol>
<li><span class="snippet">Allows decoupling your client/controller from your sub system.</span> Meaning less dependencies on you client/controller, meaning changes can be made to your sub system without breaking your client/controller.</li>
<li>Can provide some heavy lifting, by combining multiple method calls into a single call. Similar to that of the adapter and builder patterns.</li>
<li>This is an useful pattern for keeping your code <span class="snippet">compliant with the law of demeter</span> aka principle of least knowledge. This is done by abstracting away the complicated code into the facade, meaning your client doesn&#8217;t have to know about the internals of anything except the facade itself.</li>
</ol>
<h2>Drawbacks</h2>
<ol>
<li>Although extremely useful the facade is often used when there is no need for it, this complicates your code needlessly.This isn&#8217;t a drawback as such, just be careful not to fall into this trap.</li>
</ol>
<h2>Example</h2>
<pre class="prettyprint linenums">
/**
 * Ok so this looks pretty terrible, right? Everything is public and crappy method names!
 */
interface SendMailInterface
{
    public function setSendToEmailAddress($emailAddress);
    public function setSubjectName($subject);
    public function setTheEmailContents($body);
    public function setTheHeaders($headers);
    public function getTheHeaders();
    public function getTheHeadersText();
    public function sendTheEmailNow();
}

/**
 * Implementing that crappy interface
 */
class SendMail implements SendMailInterface
{
    public $to, $subject, $body;
    public $headers = array();

    public function setSendToEmailAddress($emailAddress)
    {
        $this->to = $emailAddress;
    }
    
    public function setSubjectName($subject)
    {
        $this->subject = $subject;
    }

    public function setTheEmailContents($body)
    {
        $this->body = $body;
    }

    public function setTheHeaders($headers)
    {
        $this->headers = $headers;
    }

    public function getTheHeaders()
    {
        return $this->headers;
    }

    public function getTheHeadersText()
    {
        $headers = "";
        foreach ($this->getTheHeaders() as $header) {
            $headers .= $header . "\r\n";
        }
    }

    public function sendTheEmailNow()
    {
        mail($this->to, $this->subject, $this->body, $this->getTheHeadersText());
    }
}

/**
 * A facade wrapper around the crappy SendMail, to improve method names.
 */
class SendMailFacade
{
    private $sendMail;

    public function __construct(SendMailInterface $sendMail)
    {
        $this->sendMail = $sendMail;
    }

    public function setTo($to)
    {
        $this->sendMail->setSendToEmailAddress($to);
        return $this;
    }
    
    public function setSubject($subject)
    {
        $this->sendMail->setSubjectName($subject);
        return $this;
    }

    public function setBody($body)
    {
        $this->sendMail->setTheEmailContents($body);
        return $this;
    }

    public function setHeaders($headers)
    {
        $this->sendMail->setTheHeaders($headers);
        return $this;
    }

    public function send()
    {
        $this->sendMail->sendTheEmailNow();
    }
}

$to      = "bob@marley.com";
$subject = "Bob Marley and the Wailers";
$body    = "Bob Marley and the Wailers were a Jamaican reggae band created by Bob Marley, Peter Tosh and Bunny Wailer.";
$headers = array(
    "From: Steve@Irwin.com"
);

// Using the minging SendMail class
$sendMail = new SendMail();
$sendMail->setSendToEmailAddress($to);
$sendMail->setSubjectName($subject);
$sendMail->setTheEmailContents($body);
$sendMail->setTheHeaders($headers);
$sendMail->sendTheEmailNow();

// Using the sexy SendMailFacade class
$sendMail       = new SendMail();
$sendMailFacade = new sendMailFacade($sendMail);
$sendMailFacade->setTo($to)->setSubject($subject)->setBody($body)->setHeaders($headers)->send();
</pre>
]]></content:encoded>
							<wfw:commentRss>https://www.jakowicz.com/facade-pattern-in-php/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
							</item>
		<item>
		<title>Decorator pattern in PHP</title>
		<link>https://www.jakowicz.com/decorator-pattern-in-php/</link>
				<comments>https://www.jakowicz.com/decorator-pattern-in-php/#respond</comments>
				<pubDate>Fri, 23 May 2014 07:40:11 +0000</pubDate>
		<dc:creator><![CDATA[Simon]]></dc:creator>
				<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[OOP]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Decorator Pattern]]></category>
		<category><![CDATA[Structural Pattern]]></category>

		<guid isPermaLink="false">http://www.jakowicz.com/?p=872</guid>
				<description><![CDATA[This is post 8 of 13 in the series &#8220;PHP Design Patterns&#8221; The decorator pattern is another structural pattern. The aim of the decorator pattern is to extend an existing classes functionality without modifying existing classes and rather using composition to wrap and extend the existing functionality. Using Decorators, existing behaviours will stay the same,... <a class="more-link" href="https://www.jakowicz.com/decorator-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 8 of 13 in the series <em>&ldquo;PHP Design Patterns&rdquo;</em>	</p>

	
	</aside>
<h2>The decorator pattern is another structural pattern. The aim of the decorator pattern is to extend an existing classes functionality without modifying existing classes and rather using composition to wrap and extend the existing functionality.</h2>
<p>Using Decorators, existing behaviours will stay the same, but you will have additional behaviour extensions which can be used to modify the output.</p>
<p><span id="more-872"></span></p>
<h2>What is the decorator pattern</h2>
<p>You may think this sounds quite similar to the adapter pattern. They are both similar in that they both use a wrapper to modify the end result. But as discussed in my article on the adapter pattern. Adapters should be used for allowing incompatible interfaces to work together. <span class="snippet">The decorator pattern is used to extend existing functionality.</span></p>
<h2>When to use the decorator pattern</h2>
<p>So we know that we should use the decorator pattern when we want to extend functionality, but what the hell does that mean. <span class="snippet">The whole principle of the decorator pattern is to provide a means of extending the output of a component in multiple ways using any combination of decorator classes.</span> Just like in the real world, where you have a bedroom, you may have multiple ways to decorate your room. For example these could be lamps, posters, pictures, curtains etc. It would still be possible to create an empty bedroom, but you should also be able to decorate the room with as many of the available decorators as you like.</p>
<h2>How to use the decorator pattern</h2>
<ol>
<li>The first thing you want to do is create an abstract class for your component (the bedroom) and then the component itself to provide the default behaviour.</li>
<li>Next you want to create an abstract decorator which implements the components interface, this allow you to pass around and the component and decorated components interchangeably.</li>
<li>The abstract decorator should have a constructor which is passed an instance of the component. If the component has already be wrapped by a decorator this could be passed instead. This means your component can be wrapped by a decorator and you then your decorated component can then be wrapped by another decorator. Rinse, repeat.</li>
<li>Create a collection of concrete decorators (posters, lamps etc) which all implement your abstract decorator.</li>
<li>Each concrete decorator should make a call to its encapsulated component or decorated component. This allows multiple decorators to be able to wrap each other.</li>
</ol>
<h2>Rules</h2>
<ol>
<li>The abstract decorator should extend the components abstract class, <span class="snippet">this allows your component and decorators to work interchangeably within other decorators.</span></li>
<li><span class="snippet">Abstract decorators can provide some default values</span> for the concrete decorators. I&#8217;ll give an example of this in the example section below.</li>
<li>All decorators should implement your abstract decorator.</li>
</ol>
<h2>Advantages</h2>
<ol>
<li>You are able to extend the functionality of your application without modifying existing interfaces. So you <span class="snippet">comply to the interface segregation principle.</span></li>
<li>You can have any number of abstract decorators extend other abstract decorators. Allowing you to create a tree like structure of decorators.</li>
<li>Decorators are a nice<span class="snippet"> flexible alternative to subclassing.</span></li>
</ol>
<h2>Drawbacks</h2>
<ol>
<li>Decorators usually result in lots of tiny classes. <span class="snippet">Over use of decorators can become confusing.</span></li>
<li>Class initialisation is more complicated than usual, because you have to initialise the component and then wrap the decorators around it.</li>
<li>Creating a large decorator tree is highly confusing. I recommend to <span class="snippet">never have a hierarchy of more than 2 decorators. 3 is painful, 4+ is insane.</span></li>
</ol>
<h2>Example</h2>
<pre class="prettyprint linenums">
interface RoomInterface
{
    public function getContents();
}

class Bedroom implements RoomInterface
{
    public function getContents()
    {
        return "So you have a bedroom.\n";
    }
}

class Bathroom implements RoomInterface
{
    public function getContents()
    {
        return "So you have a bathroom.\n";
    }
}

abstract class RoomDecoratorAbstract implements RoomInterface
{
    protected $room;
    private   $contentText;

    public function __construct(RoomInterface $room)
    {
        $this->room = $room;
    }

    protected abstract function styleContentText($text);
}

abstract class BedroomDecoratorAbstract extends RoomDecoratorAbstract
{
    protected function styleContentText($text)
    {
        return " - " . $text . "\n";
    }
}

abstract class BathroomDecoratorAbstract extends RoomDecoratorAbstract
{
    protected function styleContentText($text)
    {
        return " # " . $text . "\n";
    }
}

class BedroomPosterDecorator extends BedroomDecoratorAbstract
{
    private $contentText = "There is a mudder fudging poster in it.";
    
    public function getContents()
    {
        return $this->room->getContents() . $this->styleContentText($this->contentText);
    }
}

class BedroomLampDecorator extends BedroomDecoratorAbstract
{
    private $contentText = "One does not simply have a lamp, without it containing artificial lava.";

    public function getContents()
    {
        return $this->room->getContents() . $this->styleContentText($this->contentText);
    }
}

class BedroomBedDecorator extends BedroomDecoratorAbstract
{
    private $contentText = "You have a bed with a 40,000 spring mattress, 1,000 tog duvet and pillows made of bacon.";

    public function getContents()
    {
        return $this->room->getContents() . $this->styleContentText($this->contentText);
    }
}

class BathroomBogDecorator extends BathroomDecoratorAbstract
{
    private $contentText = "There is a bog to do the business.";
    
    public function getContents()
    {
        return $this->room->getContents() . $this->styleContentText($this->contentText);
    }
}

class BathroomShowerDecorator extends BathroomDecoratorAbstract
{
    private $contentText = "Look!! A brand new Aqualisa Quartz digital shower. Oooooooo.";

    public function getContents()
    {
        return $this->room->getContents() . $this->styleContentText($this->contentText);
    }
}

class BathroomBasinDecorator extends BathroomDecoratorAbstract
{
    private $contentText = "Diamond taps and it even comes with a plug. Bang for your buck";

    public function getContents()
    {
        return $this->room->getContents() . $this->styleContentText($this->contentText);
    }
}

$bedroom         = new Bedroom();
$posterDecorator = new BedroomPosterDecorator($bedroom);
$lampDecorator   = new BedroomLampDecorator($posterDecorator);
$bedDecorator    = new BedroomBedDecorator($lampDecorator);

// So you have a bedroom.
echo $bedroom->getContents();

// So you have a bedroom.
// - There is a mudder fudging poster in it.
echo $posterDecorator->getContents();

// So you have a bedroom.
// - There is a mudder fudging poster in it.
// - One does not simply have a lamp, without it containing artificial lava.
echo $lampDecorator->getContents();

// So you have a bedroom.
// - There is a mudder fudging poster in it.
// - One does not simply have a lamp, without it containing artificial lava.
// - You have a bed with a 40,000 spring mattress, 1,000 tog duvet and pillows made of bacon.
echo $bedDecorator->getContents();

$bathroom        = new Bathroom();
$bogDecorator    = new BathroomBogDecorator($bathroom);
$showerDecorator = new BathroomShowerDecorator($bogDecorator);
$basinDecorator  = new BathroomBasinDecorator($showerDecorator);

// So you have a bathroom.
echo $bathroom->getContents();

// So you have a bathroom.
// # There is a bog to do the business.
echo $bogDecorator->getContents();

// So you have a bathroom.
// # There is a bog to do the business.
// # Look!! A brand new Aqualisa Quartz digital shower. Oooooooo.
echo $showerDecorator->getContents();

// So you have a bathroom.
// # There is a bog to do the business.
// # Look!! A brand new Aqualisa Quartz digital shower. Oooooooo.
// # Diamond taps and it even comes with a plug. Bang for your buck
echo $basinDecorator->getContents();
</pre>
]]></content:encoded>
							<wfw:commentRss>https://www.jakowicz.com/decorator-pattern-in-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
							</item>
		<item>
		<title>Adapter Pattern in PHP</title>
		<link>https://www.jakowicz.com/adapter-pattern-in-php/</link>
				<comments>https://www.jakowicz.com/adapter-pattern-in-php/#comments</comments>
				<pubDate>Mon, 28 Apr 2014 22:25:54 +0000</pubDate>
		<dc:creator><![CDATA[Simon]]></dc:creator>
				<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[OOP]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Adapter Pattern]]></category>
		<category><![CDATA[Structural Pattern]]></category>

		<guid isPermaLink="false">http://www.jakowicz.com/?p=858</guid>
				<description><![CDATA[This is post 7 of 13 in the series &#8220;PHP Design Patterns&#8221; Now we have covered all of the creational patterns you should know about (imo). I am steaming ahead on to the structural patterns. The first of which is the adapter pattern 😀 In programming, it&#8217;s not rare to build a system, to find... <a class="more-link" href="https://www.jakowicz.com/adapter-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 7 of 13 in the series <em>&ldquo;PHP Design Patterns&rdquo;</em>	</p>

	
	</aside>
<h2>Now we have covered all of the creational patterns you should know about (imo). I am steaming ahead on to the structural patterns. The first of which is the adapter pattern <img src="https://s.w.org/images/core/emoji/11.2.0/72x72/1f600.png" alt="😀" class="wp-smiley" style="height: 1em; max-height: 1em;" /></h2>
<p>In programming, it&#8217;s not rare to build a system, to find out a few months down the line, there are a bunch of new requirements. Originally catering for a particular client or data set and then later having to cater for more and more, this is where the adapter pattern comes into play.</p>
<p><span id="more-858"></span></p>
<h2>What is the Adapter pattern</h2>
<p>The adapter pattern is also <span class="snippet">commonly called the wrapper pattern,</span> because that&#8217;s exactly what it&#8217;s doing. You build a class and then you have to write a wrapper/adapter that encapsulate the existing class and slightly manipulates the way it work.</p>
<p>A real world example of this is a main power adapter, your 3 pin plug may work in the uk, but when you go to america, you need an adapter to convert the 3 pin plug into a 2 pin plug.</p>
<p>What is important when building an adapter is that you <span class="snippet">do not change the behaviour of the original object</span> (the 3 pin plug), all you do is create an adapter to allow the 3 pin plug to work in different environments.</p>
<h2>Inheritance Vs Composition</h2>
<p>There are two versions of the adapter pattern. The inheritance version also known as the class version and the composition version also known as the object version. As you hopefully know, in programming <span class="snippet">composition is always favoured over inheritance,</span> due to its looser bindings. For this reason I&#8217;ll only be demonstrating the composition version it is entirety, but here is a low down on the inheritance version.</p>
<h2>Inheritance</h2>
<p>When using the inheritance version, you <span class="snippet">rely on your adapter class having multiple inheritance.</span> First it should inherit the class it is adapting (think of this as the 3 pin plug) and secondly it should inherit an adapter target class with a collection of adapter methods (think of this as the 2 pin plug). <span class="snippet">PHP however does not support multiple inheritance out the box,</span> apart from traits which aren&#8217;t built for this type of scenario. PHP also supports being able to inherit from one class and implement from another.</p>
<p>The correct way to use this pattern would be to <span class="snippet">inherit from the class being adapted (3 pin plug) and then implement an interface which would define all of the adapter methods (2 pin plug).</span> Using inheritance over composition has the <span class="snippet">benefit of not having to define wrappers for methods which do not require any changes.</span> However there is no harm in creating these wrappers in fact I prefer this clarity and it is the recommended choice&#8230;.. so I won&#8217;t be discussing inheritance any further.</p>
<p>If you don&#8217;t understand the inheritance concept. Don&#8217;t worry, I&#8217;ve not explained it great, because you&#8217;ll never really have a need for it in PHP. You&#8217;re better of grasping composition and than re-reading over the inheritance version if you&#8217;re still interested.</p>
<h2>Composition</h2>
<p>Composition is by far the better known and more commonly used version of the adapter pattern. It relies on your adapter (2 pin plug) being a wrapper for your already existing adaptee class (3 pin plug). <span class="snippet">All you&#8217;re effectively doing is creating an adapter class, passing the adapter an instance of the adaptee and then redefining each of the adaptees methods so they can be called from within the adapter.</span> This allows you to rename methods or even merge multiple methods into one. Thus complying to the new interface requirements.</p>
<h2>When to use</h2>
<p>As I described above, adapters are used in the real world all the time. Rather than adapting an already existing module and potentially breaking everything. It makes much more sense to make an independent adapter to modify the existing functionality whilst keeping the adaptee fully functional.</p>
<p>Going back to the 2 pin plug adapter idea, you could rewire the 3 pin plug into the 2 pin plug but you&#8217;re more liable to break both plugs, where if you create an adapter for the 3 pin plug. The 3 pin plug stays unmodified and you can keep tampering with the 2 pin adapter until it works. Put more simply, you should use the adapter pattern <span class="snippet">when you need incompatible interfaces to work together.</span> Without breaking existing functionality.</p>
<h2>Rules</h2>
<ol>
<li>Do not modify existing components. If you do you risk breaking old functionality and make using an adapter pointless all together.</li>
</ol>
<h2>Drawbacks</h2>
<p>There are no real drawbacks to using the adapter pattern. However there is a fair point, that instead of creating an adapter pattern, code could be refactored instead. If you do not rely on any 3rd parties and you’re programming to an interface, like you should be. You would be able to create a new class with the same interface. Doing so will keep your code much cleaner and maintainable. <span class="snippet">If however you rely on using 3rd party code it can become extremely handy to create adapters to make incompatible systems work in harmony.</span></p>
<h2>Example</h2>
<p>Note: I have dropped adding tonnes of doc-block. As much as I do like them, I&#8217;m starting to thing they&#8217;re a little OTT for a blog.</p>
<pre class="prettyprint linenums">
/**
 * interface for creating render classes
 */
interface RenderTemplateInterface 
{
    public function renderHeader();
    public function renderBody();
    public function renderFooter();
}

/**
 * Used for rendering HTML templates
 */
class RenderHTMLTemplate implements RenderTemplateInterface 
{

    public function renderHeader() 
    {
        return "&lt;html&gt;&lt;body&gt;";
    }

    public function renderBody() 
    {
        return "Hello World";
    }

    public function renderFooter() 
    {
        return "&lt;/body&gt;&lt;/html&gt;";
    }

}

/**
 * Separate interface just for rendering PDF's
 * Having a separate interface from RenderTemplateInterface could be a requirement from a third party
 */
interface PDFTemplateInterface 
{
    public function renderTop();
    public function renderMiddle();
    public function renderBottom();
}

/**
 * Used for rendering PDF templates
 */
class RenderPDFTemplate implements PDFTemplateInterface 
{

    public function renderTop() 
    {
        return "This is the top of the PDF";
    }

    public function renderMiddle() 
    {
        return "Hello World";
    }

    public function renderBottom() 
    {
        return "This is the bottom of the PDF";
    }

}

/**
 * The adapter - this will encapsulate an instance of the RenderPDFTemplate class
 * to work polymorphically with the RenderTemplateInterface interface
 */
class PDFTemplateAdapter implements RenderTemplateInterface
{
    private $pdfTemplate;

    public function __construct(PDFTemplateInterface $pdfTemplate)
    {
        $this->pdfTemplate = $pdfTemplate;
    }

    public function renderHeader() 
    {
        return $this->pdfTemplate->renderTop();
    }

    public function renderBody() 
    {
        return $this->pdfTemplate->renderMiddle();
    }

    public function renderFooter() 
    {
        return $this->pdfTemplate->renderBottom();
    }
}

$pdfTemplate = new RenderPDFTemplate();

// $pdfTemplateAdapter will implement RenderTemplateInterface, just like RenderHTMLTemplate does
$pdfTemplateAdapter = new PDFTemplateAdapter($pdfTemplate);

// This is the top of the PDF
echo $pdfTemplateAdapter->renderHeader();
</pre>
]]></content:encoded>
							<wfw:commentRss>https://www.jakowicz.com/adapter-pattern-in-php/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
							</item>
		<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>
	</channel>
</rss>
