<?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>the fancy part of the web &#187; pattern</title>
	<atom:link href="http://blog.tolleiv.de/tag/pattern/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.tolleiv.de</link>
	<description>is elsewhere - this is just about all sorts of web related work with a small factor of fanciness</description>
	<lastBuildDate>Sat, 21 Jan 2012 12:58:05 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Signal / Slots in Extbase</title>
		<link>http://blog.tolleiv.de/2011/11/signal-slots-in-extbase/</link>
		<comments>http://blog.tolleiv.de/2011/11/signal-slots-in-extbase/#comments</comments>
		<pubDate>Wed, 30 Nov 2011 17:17:02 +0000</pubDate>
		<dc:creator>tolleiv</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[pattern]]></category>
		<category><![CDATA[typo3]]></category>
		<category><![CDATA[extbase]]></category>

		<guid isPermaLink="false">http://blog.tolleiv.de/?p=758</guid>
		<description><![CDATA[A nice thing to have at hand is definately Signal and Slots. I heard Felix talking about them quite often and I finally found a nice usecase and came to play with them a little bit this afternoon. And just to avoid that others have to look around too much to find how they ...]]></description>
			<content:encoded><![CDATA[<p>A nice thing to have at hand is definately <a href="http://en.wikipedia.org/wiki/Signals_and_slots">Signal and Slots</a>. I heard <a href="http://f.oer.tel">Felix</a> talking about them quite often and I finally found a nice usecase and came to play with them a little bit this afternoon. And just to avoid that others have to look around too much to find how they can get them to work here&#8217;s how it&#8217;s working for me.</p>
<p>First of all you should understand the concept. This nice little &#8220;definition&#8221; (from <a href="http://flow3.typo3.org/documentation/guide/partiii/signalsandslots.html">flow3.typo3.org</a>) sums it up pretty well:</p>
<blockquote><p>A signal, which contains event information as it makes sense in the case at hand, can be emitted (sent) by any part of the code and is received by one or more slots, which can be any function<del datetime="2011-11-30T16:19:24+00:00"> in FLOW3</del> in extbase.</p></blockquote>
<p>To get this running in extbase, you&#8217;ve to get hold of the <em>Tx_Extbase_SignalSlot_Dispatcher</em>, which is the central instance to manage all of it. Within Extbase that&#8217;s done easily with this snippet within your classes:</p>
<pre name="code" class="php">
   ...
	/**
	 * @var Tx_Extbase_SignalSlot_Dispatcher
	 */
	protected $signalSlotDispatcher;

	/**
	 * @param Tx_Extbase_SignalSlot_Dispatcher $signalSlotDispatcher
	 */
	public function injectSignalSlotDispatcher(Tx_Extbase_SignalSlot_Dispatcher $signalSlotDispatcher) {
		$this->signalSlotDispatcher = $signalSlotDispatcher;
	}
   ...
</pre>
<p>Next thing is to make use of it. The Slot (listener) part could look like one of following blocks. In all cases you define the Signal by it&#8217;s class (not necessarily a PHP Class) and it&#8217;s name. Next to that the Slot can either be defined by a Closure, an object with a method name or a PHP-Class and a method name.</p>
<pre name="code" class="php">
   ...
// Using a closure
$this->signalSlotDispatcher->connect(
      'Crunching', 'emitDataReady', function($data) { crunch($data) }, NULL, FALSE
);
   ...
// Using a method of the current object
$this->signalSlotDispatcher->connect(
     'Crunching', 'emitDataReady', $this, 'crunch', FALSE
);
   ...
// Using a method of the specified class
$this->signalSlotDispatcher->connect(
     'Crunching', 'emitDataReady', 'Cruncher', 'crunch', FALSE
);
   ...
</pre>
<p>To trigger the Signal which invokes the Slots registered above, you&#8217;ve to run the following code.</p>
<pre name="code" class="php">
$this->signalSlotDispatcher->dispatch('Crunching', 'emitDataReady', array($data));
</pre>
<p>One thing I found was that by default the <em>Tx_Extbase_SignalSlot_Dispatcher</em> it not a Singleton in older extbase versions. Bastian fixed that already in the <a href="https://review.typo3.org/#change,6785">master</a> and <a href="https://review.typo3.org/#change,6786">1-4</a> branches and lucky enough this change was part within the TYPO3 4.6.1 release. But I think it&#8217;s still important to mention that this wasn&#8217;t the default from the beginning on.</p>
<p>Even if <a href="http://flow3.typo3.org/documentation/guide/partiii/signalsandslots.html">AOP is a nicer way to implement this feature</a>, the extbase backport still works pretty straigh forward.</p>
<p>Edit: One thing I&#8217;ve to add &#8211; Felix is not &#8220;just&#8221; talking about Signal/Slots &#8211; he&#8217;s the one to thank for the <a href="https://review.typo3.org/1563">backport</a>. And now that his <a href="http://blog.foertel.com/2011/10/using-signalslots-in-extbase/">blog</a> is running again &#8211; this post seems like a summary <img src='http://blog.tolleiv.de/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  </p>
<p class="wp-flattr-button"></p> <p><a href="http://blog.tolleiv.de/?flattrss_redirect&amp;id=758&amp;md5=6f525b7c42151f2d64a2bb1f506934e4" title="Flattr" target="_blank"><img src="http://blog.tolleiv.de/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.tolleiv.de/2011/11/signal-slots-in-extbase/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Iterator [GoF]</title>
		<link>http://blog.tolleiv.de/2008/07/iterator-gof/</link>
		<comments>http://blog.tolleiv.de/2008/07/iterator-gof/#comments</comments>
		<pubDate>Mon, 07 Jul 2008 17:30:00 +0000</pubDate>
		<dc:creator>tolleiv</dc:creator>
				<category><![CDATA[behavioral]]></category>
		<category><![CDATA[iterator]]></category>
		<category><![CDATA[pattern]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[spl]]></category>

		<guid isPermaLink="false">http://blog.tolleiv.de/2008/07/iterator-gof/</guid>
		<description><![CDATA[Lot's of people like to write down things into lists, so that they can go through that list later and check whether everything was fine. Normally every recipe has a list ~ there's always a list of ingredients at the beginning of the recipe.
This short example shows how such a list can be processed ...]]></description>
			<content:encoded><![CDATA[<p>Lot&#8217;s of people like to write down things into lists, so that they can go through that list later and check whether everything was fine. Normally every recipe has a list ~ there&#8217;s always a list of ingredients at the beginning of the recipe.<br />
This short example shows how such a list can be processed in PHP. So why would you want to have something else than a array to hold your objects? &#8211; My example still uses a array to hold the objects (uni- or bidirectional lists would also be possible) but it adds a kind of a facade to the array so that the common managements-tasks are handled within the List-Object. Everything you need for this example is present in PHP since version 5.0. The basic steps you need to do is to provide a <span style="font-style: italic;">&#8220;Object&#8221;</span> and an <span style="font-style: italic;">&#8220;ObjectList&#8221; </span>which implements the native <a href="http://www.php.net/manual/en/language.oop5.iterations.php"><span style="font-style: italic;">&#8220;Iterator&#8221;</span></a> interface and then you&#8217;re able to have very handy lists <img src='http://blog.tolleiv.de/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /><br />
<a onclick="document.getElementById('codeblockIt1').style.display=((document.getElementById('codeblockIt1').style.display=='block')?'none':'block');" href="#codeIt1"></a></p>
<div id="codeblockIt1" class="code">
<p><span style="color: #007700;">class </span><span style="color: #0000bb;">Incredient </span><span style="color: #007700;">{</span></p>
<p>public <span style="color: #0000bb;">$name</span><span style="color: #007700;">,</span><span style="color: #0000bb;">$amount</span><span style="color: #007700;">;<br />
public function </span><span style="color: #0000bb;">__construct</span><span style="color: #007700;">(</span><span style="color: #0000bb;">$name</span><span style="color: #007700;">,</span><span style="color: #0000bb;">$amount</span><span style="color: #007700;">) {<br />
</span><span style="color: #0000bb;">$this</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">name </span><span style="color: #007700;">= </span><span style="color: #0000bb;">$name</span><span style="color: #007700;">;<br />
</span><span style="color: #0000bb;">$this</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">amount </span><span style="color: #007700;">= </span><span style="color: #0000bb;">$amount</span><span style="color: #007700;">;<br />
}<br />
}</span></p>
<p>class <span style="color: #0000bb;">Recipe </span><span style="color: #007700;">implements </span><span style="color: #0000bb;">Iterator </span><span style="color: #007700;">{<br />
public </span><span style="color: #0000bb;">$title</span><span style="color: #007700;">;<br />
private </span><span style="color: #0000bb;">$ingredients</span><span style="color: #007700;">;</span></p>
<p>public function <span style="color: #0000bb;">__construct </span><span style="color: #007700;">(</span><span style="color: #0000bb;">$title</span><span style="color: #007700;">) {<br />
</span><span style="color: #0000bb;">$this</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">title </span><span style="color: #007700;">= </span><span style="color: #0000bb;">$title</span><span style="color: #007700;">;<br />
}</span></p>
<p>public function <span style="color: #0000bb;">addIncredient</span><span style="color: #007700;">(</span><span style="color: #0000bb;">Incredient $in</span><span style="color: #007700;">) {<br />
</span><span style="color: #0000bb;">$this</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">ingredients</span><span style="color: #007700;">[] = </span><span style="color: #0000bb;">$in</span><span style="color: #007700;">;<br />
}</span></p>
<p>public function <span style="color: #0000bb;">current </span><span style="color: #007700;">()  {   return </span><span style="color: #0000bb;">current </span><span style="color: #007700;">(</span><span style="color: #0000bb;">$this</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">ingredients</span><span style="color: #007700;">);    }<br />
public function </span><span style="color: #0000bb;">key </span><span style="color: #007700;">()      {   return </span><span style="color: #0000bb;">key</span><span style="color: #007700;">(</span><span style="color: #0000bb;">$this</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">ingredients</span><span style="color: #007700;">);         }<br />
public function </span><span style="color: #0000bb;">valid </span><span style="color: #007700;">()    {   return </span><span style="color: #0000bb;">current </span><span style="color: #007700;">(</span><span style="color: #0000bb;">$this</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">ingredients</span><span style="color: #007700;">);    }<br />
public function </span><span style="color: #0000bb;">rewind </span><span style="color: #007700;">()   {   return </span><span style="color: #0000bb;">reset </span><span style="color: #007700;">(</span><span style="color: #0000bb;">$this</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">ingredients</span><span style="color: #007700;">);      }<br />
public function </span><span style="color: #0000bb;">next </span><span style="color: #007700;">()     {   return </span><span style="color: #0000bb;">next </span><span style="color: #007700;">(</span><span style="color: #0000bb;">$this</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">ingredients</span><span style="color: #007700;">);       }<br />
}</span></p>
<p><!-- Code end --></p>
</div>
<div id="codeblockIt2" class="code" style="display: block;">
<p><span style="color: #0000bb;">$cookieRecipe </span><span style="color: #007700;">= new </span><span style="color: #0000bb;">Recipe</span><span style="color: #007700;">(</span><span style="color: #dd0000;">&#8220;Chocolate Cookie&#8221;</span><span style="color: #007700;">);<br />
</span><span style="color: #0000bb;">$cookieRecipe</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">addIncredient</span><span style="color: #007700;">(new </span><span style="color: #0000bb;">Incredient</span><span style="color: #007700;">(</span><span style="color: #dd0000;">&#8216;Flour&#8217;</span><span style="color: #007700;">,</span><span style="color: #dd0000;">&#8217;2.5 cups&#8217;</span><span style="color: #007700;">));<br />
</span><span style="color: #0000bb;">$cookieRecipe</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">addIncredient</span><span style="color: #007700;">(new </span><span style="color: #0000bb;">Incredient</span><span style="color: #007700;">(</span><span style="color: #dd0000;">&#8216;Baking soda&#8217;</span><span style="color: #007700;">,</span><span style="color: #dd0000;">&#8217;1 teaspoon&#8217;</span><span style="color: #007700;">));<br />
</span><span style="color: #0000bb;">$cookieRecipe</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">addIncredient</span><span style="color: #007700;">(new </span><span style="color: #0000bb;">Incredient</span><span style="color: #007700;">(</span><span style="color: #dd0000;">&#8216;Salt&#8217;</span><span style="color: #007700;">,</span><span style="color: #dd0000;">&#8217;0.5 teaspoon&#8217;</span><span style="color: #007700;">));<br />
</span><span style="color: #0000bb;">$cookieRecipe</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">addIncredient</span><span style="color: #007700;">(new </span><span style="color: #0000bb;">Incredient</span><span style="color: #007700;">(</span><span style="color: #dd0000;">&#8216;Butter&#8217;</span><span style="color: #007700;">,</span><span style="color: #dd0000;">&#8217;1 cup&#8217;</span><span style="color: #007700;">));<br />
</span><span style="color: #0000bb;">$cookieRecipe</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">addIncredient</span><span style="color: #007700;">(new </span><span style="color: #0000bb;">Incredient</span><span style="color: #007700;">(</span><span style="color: #dd0000;">&#8216;Sugar&#8217;</span><span style="color: #007700;">,</span><span style="color: #dd0000;">&#8217;1 cup&#8217;</span><span style="color: #007700;">));<br />
</span><span style="color: #0000bb;">$cookieRecipe</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">addIncredient</span><span style="color: #007700;">(new </span><span style="color: #0000bb;">Incredient</span><span style="color: #007700;">(</span><span style="color: #dd0000;">&#8216;Brown Sugar&#8217;</span><span style="color: #007700;">,</span><span style="color: #dd0000;">&#8217;0.5 cup&#8217;</span><span style="color: #007700;">));<br />
</span><span style="color: #0000bb;">$cookieRecipe</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">addIncredient</span><span style="color: #007700;">(new </span><span style="color: #0000bb;">Incredient</span><span style="color: #007700;">(</span><span style="color: #dd0000;">&#8216;Vanilla extract&#8217;</span><span style="color: #007700;">,</span><span style="color: #dd0000;">&#8217;1 teaspoon&#8217;</span><span style="color: #007700;">));<br />
</span><span style="color: #0000bb;">$cookieRecipe</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">addIncredient</span><span style="color: #007700;">(new </span><span style="color: #0000bb;">Incredient</span><span style="color: #007700;">(</span><span style="color: #dd0000;">&#8216;Egg&#8217;</span><span style="color: #007700;">,</span><span style="color: #dd0000;">&#8217;1-2&#8242;</span><span style="color: #007700;">));<br />
</span><span style="color: #0000bb;">$cookieRecipe</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">addIncredient</span><span style="color: #007700;">(new </span><span style="color: #0000bb;">Incredient</span><span style="color: #007700;">(</span><span style="color: #dd0000;">&#8216;Chocolate chips&#8217;</span><span style="color: #007700;">,</span><span style="color: #dd0000;">&#8217;2 cups&#8217;</span><span style="color: #007700;">));</span></p>
<p><span style="color: #ff8000;">// process recipe:<br />
</span><span style="color: #007700;">foreach(</span><span style="color: #0000bb;">$cookieRecipe </span><span style="color: #007700;">as </span><span style="color: #0000bb;">$inc</span><span style="color: #007700;">) {<br />
echo </span><span style="color: #0000bb;">$inc</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">name</span><span style="color: #007700;">.</span><span style="color: #dd0000;">&#8220; =&gt; &#8221;</span><span style="color: #007700;">.</span><span style="color: #0000bb;">$inc</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">amount</span><span style="color: #007700;">.</span><span style="color: #dd0000;">&#8220;&lt;br/&gt;&#8221;</span><span style="color: #007700;">;<br />
}</span></p>
</div>
<p>As you see it&#8217;s pretty easy to have lists of objects in PHP. You might also think that always creating to some list-object over and over again is very odd and you&#8217;re right. For the most common tasks like <a href="http://www.php.net/manual/en/class.arrayiterator.php">iterating through arrays</a>, <a href="http://www.php.net/manual/en/class.directoryiterator.php">directory-lists</a> and a few more task you can use objects which are shipped with the Standard PHP Library ,which is also part of PHP since version 5 and mandatory in 5.3. So the example shown above could also look like this:</p>
<div id="codeblockIt3" class="code" style="display: block;">
<p><span style="color: #0000bb;">$recipe </span><span style="color: #007700;">= array();<br />
</span><span style="color: #0000bb;">$recipe</span><span style="color: #007700;">[] = new </span><span style="color: #0000bb;">Incredient</span><span style="color: #007700;">(</span><span style="color: #dd0000;">&#8216;Flour&#8217;</span><span style="color: #007700;">,</span><span style="color: #dd0000;">&#8217;2.5 cups&#8217;</span><span style="color: #007700;">);<br />
</span><span style="color: #0000bb;">$recipe</span><span style="color: #007700;">[] = new </span><span style="color: #0000bb;">Incredient</span><span style="color: #007700;">(</span><span style="color: #dd0000;">&#8216;Baking soda&#8217;</span><span style="color: #007700;">,</span><span style="color: #dd0000;">&#8217;1 teaspoon&#8217;</span><span style="color: #007700;">);<br />
</span><span style="color: #0000bb;">$recipe</span><span style="color: #007700;">[] = new </span><span style="color: #0000bb;">Incredient</span><span style="color: #007700;">(</span><span style="color: #dd0000;">&#8216;Salt&#8217;</span><span style="color: #007700;">,</span><span style="color: #dd0000;">&#8217;0.5 teaspoon&#8217;</span><span style="color: #007700;">);<br />
</span><span style="color: #0000bb;">$recipe</span><span style="color: #007700;">[] = new </span><span style="color: #0000bb;">Incredient</span><span style="color: #007700;">(</span><span style="color: #dd0000;">&#8216;Butter&#8217;</span><span style="color: #007700;">,</span><span style="color: #dd0000;">&#8217;1 cup&#8217;</span><span style="color: #007700;">);<br />
</span><span style="color: #0000bb;">$recipe</span><span style="color: #007700;">[] = new </span><span style="color: #0000bb;">Incredient</span><span style="color: #007700;">(</span><span style="color: #dd0000;">&#8216;Sugar&#8217;</span><span style="color: #007700;">,</span><span style="color: #dd0000;">&#8217;1 cup&#8217;</span><span style="color: #007700;">);<br />
</span><span style="color: #0000bb;">$recipe</span><span style="color: #007700;">[] = new </span><span style="color: #0000bb;">Incredient</span><span style="color: #007700;">(</span><span style="color: #dd0000;">&#8216;Brown Sugar&#8217;</span><span style="color: #007700;">,</span><span style="color: #dd0000;">&#8217;0.5 cup&#8217;</span><span style="color: #007700;">);<br />
</span><span style="color: #0000bb;">$recipe</span><span style="color: #007700;">[] = new </span><span style="color: #0000bb;">Incredient</span><span style="color: #007700;">(</span><span style="color: #dd0000;">&#8216;Vanilla extract&#8217;</span><span style="color: #007700;">,</span><span style="color: #dd0000;">&#8217;1 teaspoon&#8217;</span><span style="color: #007700;">);<br />
</span><span style="color: #0000bb;">$recipe</span><span style="color: #007700;">[] = new </span><span style="color: #0000bb;">Incredient</span><span style="color: #007700;">(</span><span style="color: #dd0000;">&#8216;Egg&#8217;</span><span style="color: #007700;">,</span><span style="color: #dd0000;">&#8217;1-2&#8242;</span><span style="color: #007700;">);<br />
</span><span style="color: #0000bb;">$recipe</span><span style="color: #007700;">[] = new </span><span style="color: #0000bb;">Incredient</span><span style="color: #007700;">(</span><span style="color: #dd0000;">&#8216;Chocolate chips&#8217;</span><span style="color: #007700;">,</span><span style="color: #dd0000;">&#8217;2 cups&#8217;</span><span style="color: #007700;">);</span></p>
<p><span style="color: #0000bb;">$recipeIncObj </span><span style="color: #007700;">= new </span><span style="color: #0000bb;">ArrayObject</span><span style="color: #007700;">(</span><span style="color: #0000bb;">$recipe</span><span style="color: #007700;">);<br />
</span><span style="color: #0000bb;">$ingredientsIt </span><span style="color: #007700;">= </span><span style="color: #0000bb;">$recipeIncObj</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">getIterator</span><span style="color: #007700;">(); </span></p>
<p>foreach(<span style="color: #0000bb;">$ingredientsIt </span><span style="color: #007700;">as </span><span style="color: #0000bb;">$inc</span><span style="color: #007700;">) {<br />
echo </span><span style="color: #0000bb;">$inc</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">name</span><span style="color: #007700;">.</span><span style="color: #dd0000;">&#8220; =&gt; &#8221;</span><span style="color: #007700;">.</span><span style="color: #0000bb;">$inc</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">amount</span><span style="color: #007700;">.</span><span style="color: #dd0000;">&#8220;&lt;br/&gt;&#8221;</span><span style="color: #007700;">;<br />
} </span></p>
</div>
<p>As I said at the beginning, there are lots of situations where you might want to have a list for something and if you store that list in PHP the Iterator-pattern can keep your code clean and tasty <img src='http://blog.tolleiv.de/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p class="wp-flattr-button"></p> <p><a href="http://blog.tolleiv.de/?flattrss_redirect&amp;id=585&amp;md5=1dde71e3068f7f29863578a1a14f9ca9" title="Flattr" target="_blank"><img src="http://blog.tolleiv.de/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.tolleiv.de/2008/07/iterator-gof/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Null-Object Pattern</title>
		<link>http://blog.tolleiv.de/2008/07/null-object-pattern/</link>
		<comments>http://blog.tolleiv.de/2008/07/null-object-pattern/#comments</comments>
		<pubDate>Tue, 01 Jul 2008 17:58:00 +0000</pubDate>
		<dc:creator>tolleiv</dc:creator>
				<category><![CDATA[behavioral]]></category>
		<category><![CDATA[null]]></category>
		<category><![CDATA[pattern]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://blog.tolleiv.de/2008/07/null-object-pattern/</guid>
		<description><![CDATA[Very often you create a object with a factory and before you really start using it, you check if your factory really created a object or returned NULL. Or maybe you have a method where a object is passed in and in this situation you'll have to do this check also.

Instead of typing the ...]]></description>
			<content:encoded><![CDATA[<p>Very often you create a object with a factory and before you really start using it, you check if your factory really created a object or returned NULL. Or maybe you have a method where a object is passed in and in this situation you&#8217;ll have to do this check also.</p>
<p>Instead of typing the &#8220;<span style="font-style: italic;">if(object == null)</span>&#8221; phrase again and again, you could use the <span style="font-weight: bold;">Null-Object pattern</span>, you&#8217;ll see that this can make some situations much clearer.</p>
<p>Basically Null-Object ensures that the client always receives a valid object for it&#8217;s interaction, so that there&#8217;s no need to do the check shown above again and again. This happens since your concrete Null-Object just shares the interface, or inherits from the same class as it&#8217;s effective counterpart, but it&#8217;s implementation just leaves out any effectiveness.<br />
<a href="http://bp3.blogger.com/_l5fIZzJyYfc/SGpiDZ9m-rI/AAAAAAAAACo/nVuiUHE4E90/s1600-h/nullobject_pattern.png" onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" rel="lightbox[584]"><br />
<img id="BLOGGER_PHOTO_ID_5218090928910564018" style="margin: 0px auto 10px; display: block; text-align: center; cursor: pointer;" src="http://bp3.blogger.com/_l5fIZzJyYfc/SGpiDZ9m-rI/AAAAAAAAACo/nVuiUHE4E90/s400/nullobject_pattern.png" border="0" alt="" /></a> So a code-example could look like this:</p>
<p><!-- Code start --><br />
<span style="color: #007700;">class </span><span style="color: #0000bb;">CookieFactory </span><span style="color: #007700;">{<br />
public function </span><span style="color: #0000bb;">makeInstance</span><span style="color: #007700;">() {<br />
if(</span><span style="color: #0000bb;">date</span><span style="color: #007700;">(</span><span style="color: #dd0000;">&#8216;l&#8217;</span><span style="color: #007700;">)==</span><span style="color: #dd0000;">&#8216;Monday&#8217;</span><span style="color: #007700;">) return new </span><span style="color: #0000bb;">NullCookie</span><span style="color: #007700;">();<br />
return new </span><span style="color: #0000bb;">RealCookie</span><span style="color: #007700;">();<br />
}<br />
}</span></p>
<p>interface <span style="color: #0000bb;">iCookie </span><span style="color: #007700;">{<br />
function </span><span style="color: #0000bb;">getCalories</span><span style="color: #007700;">();<br />
}</span></p>
<p>class <span style="color: #0000bb;">RealCookie </span><span style="color: #007700;">implements </span><span style="color: #0000bb;">iCookie </span><span style="color: #007700;">{<br />
protected </span><span style="color: #0000bb;">$calories</span><span style="color: #007700;">=</span><span style="color: #0000bb;">250</span><span style="color: #007700;">;<br />
public function </span><span style="color: #0000bb;">getCalories</span><span style="color: #007700;">() {<br />
return </span><span style="color: #0000bb;">$this</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">calories</span><span style="color: #007700;">;<br />
}<br />
}</span></p>
<p>class <span style="color: #0000bb;">NullCookie </span><span style="color: #007700;">implements </span><span style="color: #0000bb;">iCookie </span><span style="color: #007700;">{<br />
public function </span><span style="color: #0000bb;">getCalories</span><span style="color: #007700;">() {<br />
return </span><span style="color: #0000bb;">0</span><span style="color: #007700;">;<br />
}<br />
}<br />
</span><br />
<!-- Code end --></p>
<p>I think you can imagine what happens when you make use of the CookieFactory -<span style="font-style: italic;"> diet on monday <img src='http://blog.tolleiv.de/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </span><span> </span><span style="font-style: italic;"><br />
</span><br />
There&#8217;re also some disadvantages, your clients normally don&#8217;t have a chance to react that there&#8217;s something special </span><span>happening, also the clients must &#8220;share&#8221; the same expectation what &#8220;do nothing&#8221; means, </span></span>the number of required Null-Objects might be very large and unhandy and the Null-Object shares a very deep knowledge with the real one, so that it might be a large effort to create it if the real object is complex too.</p>
<p>I&#8217;m so glad that today is tuesday <img src='http://blog.tolleiv.de/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>
<p class="wp-flattr-button"></p> <p><a href="http://blog.tolleiv.de/?flattrss_redirect&amp;id=584&amp;md5=632f5fcc5366e0bf0e098609646e3ed0" title="Flattr" target="_blank"><img src="http://blog.tolleiv.de/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.tolleiv.de/2008/07/null-object-pattern/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Query Object [PoEEA]</title>
		<link>http://blog.tolleiv.de/2008/06/query-object-poeea/</link>
		<comments>http://blog.tolleiv.de/2008/06/query-object-poeea/#comments</comments>
		<pubDate>Fri, 20 Jun 2008 17:29:00 +0000</pubDate>
		<dc:creator>tolleiv</dc:creator>
				<category><![CDATA[creational]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[factory]]></category>
		<category><![CDATA[pattern]]></category>
		<category><![CDATA[query]]></category>
		<category><![CDATA[specification]]></category>

		<guid isPermaLink="false">http://blog.tolleiv.de/2008/06/query-object-poeea/</guid>
		<description><![CDATA[Maybe you remember the Specification Pattern I explained some weeks ago. It enabled a easy and intuitive  searching within large object-collections. A drawback of my example was that I stored the objects in the memory. This can be really ineffective if you want a single object out of hundreds, because you have to ...]]></description>
			<content:encoded><![CDATA[<p>Maybe you remember the <a href="http://www.cookiepattern.com/2008/05/specification-ddd.html">Specification Pattern</a> I explained some weeks ago. It enabled a easy and intuitive  searching within large object-collections. A drawback of my example was that I stored the objects in the memory. This can be really ineffective if you want a single object out of hundreds, because you have to create all of them to see which one fits the specification.<br />
Normally you want to limit the number of objects and you also don&#8217;t store large datasets in memory. The idea of the<span style="font-style: italic;"> Query Object</span> pattern is that it enables a usage, </span><span style="font-family: trebuchet ms; font-size: 85%;">comparable to the specification pattern, for objects which are persisted in a database. The benefit is that it creates a query to exclude objects which won&#8217;t satisfy your needs and therefore you wont mess up the memory anymore.<br />
Once you have a query-object in place you should not get in touch with SQL anymore because it can encapsulate SQL completely, at least if you also have some kind of data mapping (coming soon), which is a great benefit for everyone who is not so familiar with SQL. (But don&#8217;t forget, regarding performance, SQL-optimization is a very important thing).</p>
<p>So what we need for the <span style="font-style: italic;">Query Object</span> in first place is a object, I&#8217;ll use the Cookie out of the <a href="http://www.cookiepattern.com/2008/05/specification-ddd.html">specification pattern post</a> again. Then we need criteria-objects which hold the information for a single criteria, (determined by &#8220;database-field&#8221;, &#8220;operator&#8221; and &#8220;value&#8221;) and we also need the <span style="font-style: italic;">Query Objects</span> itself to wrap up the SQL-querying and the object creation somehow.</p>
<p>A very simple example could look like this:</p>
<p><a name="code"></a><br />
<!-- Code start --><br />
<span style="color: #007700;"><br />
interface </span><span style="color: #0000bb;">Critera </span><span style="color: #007700;">{<br />
public function </span><span style="color: #0000bb;">getWhereClause</span><span style="color: #007700;">();<br />
}</span></p>
<p>class <span style="color: #0000bb;">CookieCriteria </span><span style="color: #007700;">implements </span><span style="color: #0000bb;">Critera </span><span style="color: #007700;">{</span></p>
<p>private <span style="color: #0000bb;">$operator</span><span style="color: #007700;">,</span><span style="color: #0000bb;">$field</span><span style="color: #007700;">,</span><span style="color: #0000bb;">$value</span><span style="color: #007700;">;</span></p>
<p>protected function <span style="color: #0000bb;">__construct</span><span style="color: #007700;">(</span><span style="color: #0000bb;">$operator</span><span style="color: #007700;">,</span><span style="color: #0000bb;">$field</span><span style="color: #007700;">,</span><span style="color: #0000bb;">$value</span><span style="color: #007700;">) {<br />
</span><span style="color: #0000bb;">$this</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">operator</span><span style="color: #007700;">=</span><span style="color: #0000bb;">$operator</span><span style="color: #007700;">;<br />
</span><span style="color: #0000bb;">$this</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">field</span><span style="color: #007700;">=</span><span style="color: #0000bb;">$field</span><span style="color: #007700;">;<br />
</span><span style="color: #0000bb;">$this</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">value</span><span style="color: #007700;">=</span><span style="color: #0000bb;">$value</span><span style="color: #007700;">;<br />
}</span></p>
<p>public function <span style="color: #0000bb;">getWhereClause</span><span style="color: #007700;">() {<br />
return </span><span style="color: #0000bb;">implode</span><span style="color: #007700;">(</span><span style="color: #dd0000;">&#8221; &#8220;</span><span style="color: #007700;">,array(</span><span style="color: #0000bb;">$this</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">field</span><span style="color: #007700;">,</span><span style="color: #0000bb;">$this</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">operator</span><span style="color: #007700;">,</span><span style="color: #0000bb;">$this</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">value</span><span style="color: #007700;">));<br />
}</span></p>
<p>public static function <span style="color: #0000bb;">matches</span><span style="color: #007700;">(</span><span style="color: #0000bb;">$field</span><span style="color: #007700;">,</span><span style="color: #0000bb;">$value</span><span style="color: #007700;">) {<br />
return new </span><span style="color: #0000bb;">CookieCriteria</span><span style="color: #007700;">(</span><span style="color: #dd0000;">&#8220;LIKE&#8221;</span><span style="color: #007700;">,</span><span style="color: #0000bb;">$field</span><span style="color: #007700;">,</span><span style="color: #dd0000;">&#8216;&#8221;&#8216;</span><span style="color: #007700;">.</span><span style="color: #0000bb;">$value</span><span style="color: #007700;">.</span><span style="color: #dd0000;">&#8216;&#8221;&#8216;</span><span style="color: #007700;">);<br />
}</span></p>
<p>public static function <span style="color: #0000bb;">greaterThan</span><span style="color: #007700;">(</span><span style="color: #0000bb;">$field</span><span style="color: #007700;">,</span><span style="color: #0000bb;">$value</span><span style="color: #007700;">) {<br />
return new </span><span style="color: #0000bb;">CookieCriteria</span><span style="color: #007700;">(</span><span style="color: #dd0000;">&#8220;&gt;&#8221;</span><span style="color: #007700;">,</span><span style="color: #0000bb;">$field</span><span style="color: #007700;">,</span><span style="color: #0000bb;">$value</span><span style="color: #007700;">);<br />
}<br />
}</span></p>
<p>class <span style="color: #0000bb;">CookieFinder </span><span style="color: #007700;">{<br />
protected </span><span style="color: #0000bb;">$criterias</span><span style="color: #007700;">;</span></p>
<p>public function <span style="color: #0000bb;">addCriteria</span><span style="color: #007700;">(</span><span style="color: #0000bb;">Critera $criteria</span><span style="color: #007700;">) {<br />
</span><span style="color: #0000bb;">$this</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">criterias</span><span style="color: #007700;">[] = </span><span style="color: #0000bb;">$criteria</span><span style="color: #007700;">;<br />
}</span></p>
<p>public function <span style="color: #0000bb;">generateSQL</span><span style="color: #007700;">() {<br />
</span><span style="color: #0000bb;">$sql </span><span style="color: #007700;">= </span><span style="color: #dd0000;">&#8220;SELECT * FROM cookies&#8221;</span><span style="color: #007700;">;</span></p>
<p>if(<span style="color: #0000bb;">sizeof</span><span style="color: #007700;">(</span><span style="color: #0000bb;">$this</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">criterias</span><span style="color: #007700;">)) {<br />
</span><span style="color: #0000bb;">$where</span><span style="color: #007700;">=array();<br />
</span><span style="color: #0000bb;">reset</span><span style="color: #007700;">(</span><span style="color: #0000bb;">$this</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">criterias</span><span style="color: #007700;">);<br />
while(list(,</span><span style="color: #0000bb;">$criteria</span><span style="color: #007700;">)=</span><span style="color: #0000bb;">each</span><span style="color: #007700;">(</span><span style="color: #0000bb;">$this</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">criterias</span><span style="color: #007700;">)) {<br />
</span><span style="color: #0000bb;">$where</span><span style="color: #007700;">[] = </span><span style="color: #0000bb;">$criteria</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">getWhereClause</span><span style="color: #007700;">();<br />
}<br />
</span><span style="color: #0000bb;">$sql</span><span style="color: #007700;">.= </span><span style="color: #0000bb;">sizeof</span><span style="color: #007700;">(</span><span style="color: #0000bb;">$where</span><span style="color: #007700;">)?</span><span style="color: #dd0000;">&#8221; WHERE &#8220;</span><span style="color: #007700;">.</span><span style="color: #0000bb;">implode</span><span style="color: #007700;">(</span><span style="color: #dd0000;">&#8221; AND &#8220;</span><span style="color: #007700;">,</span><span style="color: #0000bb;">$where</span><span style="color: #007700;">):</span><span style="color: #dd0000;">&#8220;&#8221;</span><span style="color: #007700;">;<br />
}<br />
return </span><span style="color: #0000bb;">$sql</span><span style="color: #007700;">;<br />
}</span></p>
<p>public function <span style="color: #0000bb;">find</span><span style="color: #007700;">() {<br />
</span><span style="color: #0000bb;">$collection </span><span style="color: #007700;">= array();<br />
if(!</span><span style="color: #0000bb;">$result </span><span style="color: #007700;">= </span><span style="color: #0000bb;">mysql_query</span><span style="color: #007700;">(</span><span style="color: #0000bb;">$this</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">generateSQL</span><span style="color: #007700;">())) {<br />
throw new </span><span style="color: #0000bb;">Exception</span><span style="color: #007700;">(</span><span style="color: #0000bb;">mysql_errno</span><span style="color: #007700;">());<br />
}<br />
while(</span><span style="color: #0000bb;">$row </span><span style="color: #007700;">= </span><span style="color: #0000bb;">mysql_fetch_assoc</span><span style="color: #007700;">(</span><span style="color: #0000bb;">$result</span><span style="color: #007700;">)) {<br />
</span><span style="color: #0000bb;">$collection</span><span style="color: #007700;">[] = new </span><span style="color: #0000bb;">Cookie</span><span style="color: #007700;">(</span><span style="color: #0000bb;">$row</span><span style="color: #007700;">[</span><span style="color: #dd0000;">'name'</span><span style="color: #007700;">],</span><span style="color: #0000bb;">$row</span><span style="color: #007700;">[</span><span style="color: #dd0000;">'flavor'</span><span style="color: #007700;">],</span><span style="color: #0000bb;">$name</span><span style="color: #007700;">[</span><span style="color: #dd0000;">'size'</span><span style="color: #007700;">]);<br />
}<br />
return </span><span style="color: #0000bb;">$collection</span><span style="color: #007700;">;<br />
}<br />
}<br />
</span><br />
<!-- Code end --></p>
<p></span><br />
Possible client code could look like this:<br />
<span style="color: #0000bb;">$finder </span><span style="color: #007700;">= new </span><span style="color: #0000bb;">CookieFinder</span><span style="color: #007700;">();<br />
</span><span style="color: #0000bb;">$finder</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">addCriteria</span><span style="color: #007700;">(</span><span style="color: #0000bb;">CookieCriteria</span><span style="color: #007700;">::</span><span style="color: #0000bb;">matches</span><span style="color: #007700;">(</span><span style="color: #dd0000;">&#8220;name&#8221;</span><span style="color: #007700;">,</span><span style="color: #dd0000;">&#8220;Granny%&#8221;</span><span style="color: #007700;">));<br />
</span><span style="color: #0000bb;">$finder</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">addCriteria</span><span style="color: #007700;">(</span><span style="color: #0000bb;">CookieCriteria</span><span style="color: #007700;">::</span><span style="color: #0000bb;">greaterThan</span><span style="color: #007700;">(</span><span style="color: #dd0000;">&#8220;size&#8221;</span><span style="color: #007700;">,</span><span style="color: #0000bb;">100</span><span style="color: #007700;">));<br />
</span><span style="color: #0000bb;">$cookies </span><span style="color: #007700;">= </span><span style="color: #0000bb;">$finder</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">find</span><span style="color: #007700;">();<br />
</span><br />
We just pick up the <span style="font-style: italic;">Query Object</span>, add one or more criteria and ask it to create the objects which fit them.</p>
<p>So this example is not as powerful as the one I used for the <a href="http://www.cookiepattern.com/2008/05/specification-ddd.html">Specification pattern</a>, but it should be a easy task to create some kind of &#8220;nested criteria objects&#8221;.<br />
Query objects normally make use of data-mapping so that you can handle various classes, stored in different tables/databases, with a single and generic Query Object. This also enables to avoid SQL-Injection, since you&#8217;re able to validate the fields and values before you sent them to your database, also some kind of database abstraction would be possible.<br />
With the &#8220;<span style="font-style: italic;">Query Object by example</span>&#8220;, which requires to build up a single object which is used as blueprint for the required objects, exists another flavor of this pattern which is very handy to use and more descriptive.<br />
But no matter which flavor you prefer, Query Objects bring some real benefits when you&#8217;ve to handle complex datasets &#8211; for smaller projects the effort might be to much so be careful where you use it.</p>
<p class="wp-flattr-button"></p> <p><a href="http://blog.tolleiv.de/?flattrss_redirect&amp;id=581&amp;md5=9a105b0742d66c49d5d7d462d0adf126" title="Flattr" target="_blank"><img src="http://blog.tolleiv.de/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.tolleiv.de/2008/06/query-object-poeea/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Plugin [PoEAA]</title>
		<link>http://blog.tolleiv.de/2008/06/plugin-poeaa/</link>
		<comments>http://blog.tolleiv.de/2008/06/plugin-poeaa/#comments</comments>
		<pubDate>Thu, 05 Jun 2008 01:11:00 +0000</pubDate>
		<dc:creator>tolleiv</dc:creator>
				<category><![CDATA[creational]]></category>
		<category><![CDATA[factory]]></category>
		<category><![CDATA[pattern]]></category>
		<category><![CDATA[plugin]]></category>

		<guid isPermaLink="false">http://blog.tolleiv.de/2008/06/plugin-poeaa/</guid>
		<description><![CDATA[I'm sure you're pretty often in the situation that you have to switch something depending on the context you're currently in. For example most people change their eating habits before summer - I also do :P

Sometimes this is what you also want to have in your software. To achieve different behaviour you normally just ...]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m sure you&#8217;re pretty often in the situation that you have to switch something depending on the context you&#8217;re currently in. For example most people change their eating habits before summer &#8211; I also do <img src='http://blog.tolleiv.de/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>
<p>Sometimes this is what you also want to have in your software. To achieve different behaviour you normally just implement two different classes or aggregates and since they have the same &#8220;meaning&#8221; they normally share a interface (a.k.a <span style="font-style: italic;">Separated Interface</span>). But who decides which implementation fits into the current environment/context?</p>
<p>The easiest way is to have a <span style="font-style: italic;">Factory Method</span> with a small condition to decide this, but this method might grow very fast if you have various options. In this situation its also a matter of form to move this decision into some kind of configuration(-file) so that there&#8217;s only on file which differs in various environments.</p>
<p><a href="http://martinfowler.com/eaaCatalog/plugin.html">Martin Fowler</a> suggests to place some kind of mapping into the configuration-file, so that your <span style="font-style: italic;">Factory</span> knows which implementation to instantiate in the current context. The key for the mapping in this case is the name of the <span style="font-style: italic;">Separated Interface</span>.</p>
<p>As you see in the example code below, there are Cookie Tins which <span style="text-decoration: line-through;">create</span> contain Cookies and depending on the current month you want to use a more or less restrictive Cookie Tin. In May, June and July you restrict your application to create max. 5 cookies, the rest of the year you don&#8217;t care <img src='http://blog.tolleiv.de/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>
<pre name="code" class="php">
	// The Separated Interface
interface CookieTin {
	public function getCookieInstance();
}

class NormalTin implements CookieTin {
	public function getCookieInstance() {
		return new Cookie();
	}
}

class DietTin implements CookieTin {
	protected $i=0;
	public function getCookieInstance() {
		return ($this->i++ < 5)?new Cookie():new NullCookie();
	}
}

// The Factory which supports Plugin-Creation
class CookieTinFactory {
	public static function getPlugin( $class ) {
		try {
			return new $GLOBALS['Plugins'][$class]();
		} catch( Exception $e) {
			// maybe call some default implementation if the mapping is wrong
		}
	}
}
</pre>
<pre name="code" class="php">
class Cookie {
	public function printCalories() {
		echo ’200 ‘;
	}
}

class NullCookie extends Cookie{
	public function printCalories() { }
}
</pre>
<pre name="code" class="php">
// This is usually in a configuration-file, normally this should
// also sit in a XML structure….

// That’s what it would be in 300 days/year
$GLOBALS['Plugins']['CookieTin'] = “NormalTin”;
// That’s what we have to turn it to before summer
if(in_array(date(‘n’),array(5,6,7))) {
	$GLOBALS['Plugins']['CookieTin'] = “DietTin”;
}

$tin = CookieTinFactory::getPlugin(‘CookieTin’);
$i=10;
while($i–) {
	$cookie = $tin->getCookieInstance();
	$cookie->printCalories();
}
</pre>
<p>A very common use-case for this is the changed behaviour in a testing-environment compared to the production-environment.<br />
There's something else in the example beside the <span style="font-style: italic;">Plugin Pattern</span> - I also made use of the <span style="font-style: italic;">Special Case (the NullCookie)</span> pattern  which I'm going to show in a future post....</p>
<p class="wp-flattr-button"></p> <p><a href="http://blog.tolleiv.de/?flattrss_redirect&amp;id=572&amp;md5=cc38f62a87757a4302f79537af4c9652" title="Flattr" target="_blank"><img src="http://blog.tolleiv.de/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.tolleiv.de/2008/06/plugin-poeaa/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Value Object [DDD]</title>
		<link>http://blog.tolleiv.de/2008/05/value-object-ddd/</link>
		<comments>http://blog.tolleiv.de/2008/05/value-object-ddd/#comments</comments>
		<pubDate>Fri, 30 May 2008 04:39:00 +0000</pubDate>
		<dc:creator>tolleiv</dc:creator>
				<category><![CDATA[behavioral]]></category>
		<category><![CDATA[pattern]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[value object]]></category>

		<guid isPermaLink="false">http://blog.tolleiv.de/2008/05/value-object-ddd/</guid>
		<description><![CDATA[This metaphor does not fit completely, and the "Money-Example" is omnipresent, but I really like the pattern and so that's the story:

Let's say you have your grannies recipe for a chocolate cookie and you want to keep this in mind, but also you like to somehow experiment with some new or different ingredients. Normally ...]]></description>
			<content:encoded><![CDATA[<p><span style="font-style: italic;">This metaphor does not fit completely, and the &#8220;Money-Example&#8221; is omnipresent, but I really like the pattern and so that&#8217;s the story:</span></p>
<p>Let&#8217;s say you have your grannies recipe for a chocolate cookie and you want to keep this in mind, but also you like to somehow experiment with some new or different ingredients. Normally you just keep in mind what you changed and later you write down the new recipe. But from time to time you might want to compare the two recipes or maybe you want to make cookies with the new and the changed recipes. In this situation it&#8217;s really good to have both written down on paper. <img src='http://blog.tolleiv.de/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>In the world of OOP you could think of a solution using the <a href="http://cookiepattern.blogspot.com/search/label/memento?max-results=100">Memento-Pattern</a> but this doesn&#8217;t really fit the situation and it&#8217;s also some kind of overhead. That&#8217;s the reason why the <span style="font-weight: bold;">Value Object</span> is the pattern of my choice.</p>
<p>So let&#8217;s look at the recipes again &#8211; we want to add and remove ingredients without modifying the original recipe and we want to compare the resulting recipes. We don&#8217;t need to track a special identity of our recipes since we&#8217;re only &#8220;collecting&#8221; ingredients.</p>
<p>The idea of the Value Object is that every every method which somehow transforms the state of a object always returns a new object and the old object stays untouched</span><span style="font-family: trebuchet ms; font-size: 85%;">. Whenever needed you should also implement a method to compare objects, I must concede that the common &#8220;Money Example&#8221; shows much better when that&#8217;s needed &#8230;</p>
<p>Another edge of this pattern in PHP is that you can use method-chaining to perform multiple actions within a single line of code. So just have a look at the example you will like it&#8217;s taste <img src='http://blog.tolleiv.de/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<pre name="code" class="php">
class Recipe {
	protected $ingredients;

	public function __construct($ingred=”) {
		$this->ingredients = implode(‘,’,array_unique(explode(‘,’,$ingred)));
	}

	public function addIncredient($ingred=”) {
		return new Recipe($this->ingredients.‘,’.$ingred);
	}

	public function removeIncredien($ingred=”) {
		return new Recipe(preg_replace(‘/,{0,1}’.$ingred.‘,{0,1}/’,”,$this->ingredients.‘,’));
	}

	public function printIncredients() {
		echo str_replace(‘,’,‘<br/>’,$this->ingredients);
	}

	public function equals(Recipe $recipe) {
		return (strcmp($this->ingredients,$recipe->ingredients)===0)?true:false;
	}
}

$granniesRecipe = new Recipe(‘flour,baking soda,sugar,salt,butter,vanilla,chocolate’);
$aNewRecipe = $granniesRecipe->addIncredient(‘lemon’);
$coconutRecipe = $granniesRecipe->removeIncredien(‘chocolate’)->addIncredient(‘coconut’);

// check if that worked:
echo ‘<br/><strong> Grannies Cookie Recipe – Incredients are:</strong><br/>’;
$granniesRecipe->printIncredients();
echo ‘<br/><strong> A new Cookie Recipe could look like:</strong><br/>’;
$aNewRecipe->printIncredients();
echo ‘<br/><strong> A coconut cookie would look like:</strong><br/>’;
$coconutRecipe->printIncredients();
</pre>
<p><span style="font-style: italic;">The implementation is a bit odd, since it only collects the names of the ingredients but not the amount, but including the amounts of incredients would not change the concept  and that&#8217;s why I left it out. I hope you got a idea how the pattern works &#8211; the main thing is that there&#8217;s no identity and that new objects are instantiated as soon as the state of the old one would change.</span></p>
<p class="wp-flattr-button"></p> <p><a href="http://blog.tolleiv.de/?flattrss_redirect&amp;id=569&amp;md5=d6f9f358f611a968ce44ad9ff5933e80" title="Flattr" target="_blank"><img src="http://blog.tolleiv.de/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.tolleiv.de/2008/05/value-object-ddd/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Prototype [GoF]</title>
		<link>http://blog.tolleiv.de/2008/05/prototype-gof/</link>
		<comments>http://blog.tolleiv.de/2008/05/prototype-gof/#comments</comments>
		<pubDate>Tue, 27 May 2008 23:17:00 +0000</pubDate>
		<dc:creator>tolleiv</dc:creator>
				<category><![CDATA[creational]]></category>
		<category><![CDATA[pattern]]></category>
		<category><![CDATA[prototype]]></category>

		<guid isPermaLink="false">http://blog.tolleiv.de/2008/05/prototype-gof/</guid>
		<description><![CDATA[Imagine a cookie-oven which produces tasty cookies with chocolate crumbles. How do you ensure that the 1000th cookie still has the same taste as the first?
You might think that this is an easy task - just write down the recipe and follow the described steps...you know the result in real life - the 1000th ...]]></description>
			<content:encoded><![CDATA[<p>Imagine a cookie-oven which produces tasty cookies with chocolate crumbles. How do you ensure that the 1000th cookie still has the same taste as the first?<br />
You might think that this is an easy task &#8211; just write down the recipe and follow the described steps&#8230;you know the result in real life &#8211; the 1000th cookie normally tasts like the 1st but you always had the &#8220;overhead&#8221; to read the recipe and go through the steps again and again.<br />
In OOP it&#8217;s much easier to follow the recipe just instantiate a new Object and  there you go&#8230; no matter if it&#8217;s the 1st or the 1000th &#8211; it&#8217;ll always <span style="text-decoration: line-through;">taste</span> look similar.<br />
But the &#8220;recipe-overhead&#8221; is still there in a way and especially when you have larger objects whose construction is time-consuming you might want to somehow get rid of it. And that&#8217;s where a <span style="font-style: italic;">Prototype</span> can help you out &#8211; you just create the first <span style="text-decoration: line-through;">Cookie</span> Object and then you use the handy magic method <span style="font-weight: bold;">__clone</span> to create new objects.<br />
Instead of just using __clone the pattern suggests a class (some kind of a factory-class) so that you can also encapsulate the creation of the objects (and also possible adjustments you might want to make after the creation/clone).</p>
<p>So the example just shows a cookie-machine which makes use of the prototype-pattern to create new cookies (depending on the cookie you throw in before)&#8230; yummy</p>
<div style="text-align: center;"><a href="http://bp0.blogger.com/_l5fIZzJyYfc/SDrXY97tyhI/AAAAAAAAABg/1sAhpbVe2kI/s1600-h/prototype_pattern.png" onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" rel="lightbox[568]"><img id="BLOGGER_PHOTO_ID_5204709143321889298" style="cursor: pointer;" src="http://bp0.blogger.com/_l5fIZzJyYfc/SDrXY97tyhI/AAAAAAAAABg/1sAhpbVe2kI/s400/prototype_pattern.png" border="0" alt="" /></a></div>
<p><a name="code1"></a><br />
<!-- Code start --></p>
<p><span style="color: #007700;">abstract class </span><span style="color: #0000bb;">Cookie </span><span style="color: #007700;">{<br />
function </span><span style="color: #0000bb;">__clone</span><span style="color: #007700;">() {    }<br />
abstract public function </span><span style="color: #0000bb;">printFlavor</span><span style="color: #007700;">();<br />
}</span></p>
<p>class <span style="color: #0000bb;">CoconutCookie </span><span style="color: #007700;">extends </span><span style="color: #0000bb;">Cookie </span><span style="color: #007700;">{<br />
public function </span><span style="color: #0000bb;">printFlavor</span><span style="color: #007700;">() {<br />
echo </span><span style="color: #dd0000;">&#8216;Coconut Flavor&lt;br/&gt;&#8217;</span><span style="color: #007700;">;<br />
}<br />
}<br />
class </span><span style="color: #0000bb;">ChocolateCookie </span><span style="color: #007700;">extends </span><span style="color: #0000bb;">Cookie </span><span style="color: #007700;">{<br />
public function </span><span style="color: #0000bb;">printFlavor</span><span style="color: #007700;">() {<br />
echo </span><span style="color: #dd0000;">&#8216;Chocolate Flavor&lt;br/&gt;&#8217;</span><span style="color: #007700;">;<br />
}<br />
}</span></p>
<p>class <span style="color: #0000bb;">CookieMachine </span><span style="color: #007700;">{<br />
protected </span><span style="color: #0000bb;">$cookie</span><span style="color: #007700;">;<br />
public function </span><span style="color: #0000bb;">__construct</span><span style="color: #007700;">(</span><span style="color: #0000bb;">Cookie $cookie</span><span style="color: #007700;">) {<br />
</span><span style="color: #0000bb;">$this</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">cookie </span><span style="color: #007700;">= </span><span style="color: #0000bb;">$cookie</span><span style="color: #007700;">;<br />
}<br />
public function </span><span style="color: #0000bb;">makeCookie</span><span style="color: #007700;">() {<br />
return clone </span><span style="color: #0000bb;">$this</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">cookie</span><span style="color: #007700;">;<br />
}<br />
}</span><br />
<!-- Code end --></p>
<p>The client-code can look like this:</p>
<p><a name="code2"></a><br />
<!-- Code start --><br />
<span style="color: #0000bb;">$coconutCookie </span><span style="color: #007700;">= new </span><span style="color: #0000bb;">CoconutCookie</span><span style="color: #007700;">();<br />
</span><span style="color: #0000bb;">$coconutCookieMachine </span><span style="color: #007700;">= new </span><span style="color: #0000bb;">CookieMachine</span><span style="color: #007700;">(</span><span style="color: #0000bb;">$coconutCookie</span><span style="color: #007700;">);</span></p>
<p><span style="color: #0000bb;">$chocolateCookie </span><span style="color: #007700;">= new </span><span style="color: #0000bb;">ChocolateCookie</span><span style="color: #007700;">();<br />
</span><span style="color: #0000bb;">$chocolateCookieMachine </span><span style="color: #007700;">= new </span><span style="color: #0000bb;">CookieMachine</span><span style="color: #007700;">(</span><span style="color: #0000bb;">$chocolateCookie</span><span style="color: #007700;">);</span></p>
<p><span style="color: #ff8000;">//while(true) {<br />
</span><span style="color: #007700;">for(</span><span style="color: #0000bb;">$i</span><span style="color: #007700;">=</span><span style="color: #0000bb;">0</span><span style="color: #007700;">;</span><span style="color: #0000bb;">$i</span><span style="color: #007700;">&lt;</span><span style="color: #0000bb;">5</span><span style="color: #007700;">;</span><span style="color: #0000bb;">$i</span><span style="color: #007700;">++) {<br />
</span><span style="color: #0000bb;">$coconutCookieMachine</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">makeCookie</span><span style="color: #007700;">()-&gt;</span><span style="color: #0000bb;">printFlavor</span><span style="color: #007700;">();<br />
</span><span style="color: #0000bb;">$chocolateCookieMachine</span><span style="color: #007700;">-&gt;</span><span style="color: #0000bb;">makeCookie</span><span style="color: #007700;">()-&gt;</span><span style="color: #0000bb;">printFlavor</span><span style="color: #007700;">();<br />
}<br />
</span><br />
<!-- Code end --></p>
<p class="wp-flattr-button"></p> <p><a href="http://blog.tolleiv.de/?flattrss_redirect&amp;id=568&amp;md5=86dd451191fdc891dbe8ee7d61c070ad" title="Flattr" target="_blank"><img src="http://blog.tolleiv.de/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.tolleiv.de/2008/05/prototype-gof/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Specification [DDD]</title>
		<link>http://blog.tolleiv.de/2008/05/specification-ddd/</link>
		<comments>http://blog.tolleiv.de/2008/05/specification-ddd/#comments</comments>
		<pubDate>Thu, 15 May 2008 14:00:00 +0000</pubDate>
		<dc:creator>tolleiv</dc:creator>
				<category><![CDATA[pattern]]></category>
		<category><![CDATA[service]]></category>
		<category><![CDATA[specification]]></category>

		<guid isPermaLink="false">http://blog.tolleiv.de/2008/05/specification-ddd/</guid>
		<description><![CDATA[Maybe sometimes the cookie tin is filled with all sorts of cookies and only some of them are what you'd like in this special moment. Often it's very easy to specify which cookie you like, but sometimes your wishes are very complex, for example if you look for grannies special cookie with chocolate, coconut ...]]></description>
			<content:encoded><![CDATA[<p>Maybe sometimes the cookie tin is filled with all sorts of cookies and only some of them are what you&#8217;d like in this special moment. Often it&#8217;s very easy to specify which cookie you like, but sometimes your wishes are very complex, for example if you look for <span style="font-style: italic;">grannies special cookie with chocolate, coconut and vanilla crumbles</span>. This could lead into a real crumby problem if you try to sort all the cookies and then <span style="text-decoration: line-through;">select</span> eat the right one.</p>
<p>In the world of OOP it&#8217;s often much harder to collect a few objects out of a large number of different objects, also combining different requirements isn&#8217;t easy and that&#8217;s where the specification pattern can help you out. It implements some basic operations to combine requirements (AND, OR, NOT) and the only thing a concrete specification for a concrete class has to do is to implement a method (isSatisfied()) which is able to determine whether a object meats a requirement or not.</p>
<p>I splitted the generic part of the script and the cookie-example. The first part just implements the methods which are needed for the combination and provides a abstract class which is extended by the specifications in the second part. As you see the specification is combined which normally encapsulates the retrieval of the objects ,for example from a database. &#8230;.just have a look it&#8217;s really easy to select the right cookie &#8230; yummy</p>
<div style="text-align: center;"><a href="http://bp2.blogger.com/_l5fIZzJyYfc/SC115dPibfI/AAAAAAAAABQ/ZZfCsWJAwDA/s1600-h/specification_sequenze.png" onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" rel="lightbox[560]"><img id="BLOGGER_PHOTO_ID_5200942774645583346" style="cursor: pointer;" src="http://bp2.blogger.com/_l5fIZzJyYfc/SC115dPibfI/AAAAAAAAABQ/ZZfCsWJAwDA/s400/specification_sequenze.png" border="0" alt="" /></a></div>
<pre name="code" class="php">
interface Specification {
	public function isSatisfiedBy($obj);
	public function _and(Specification $spec);
	public function _or(Specification $spec);
	public function _not();
}

abstract class AbstractSpecification implements Specification {
	public function isSatisfiedBy($obj) { }
	public function _and(Specification $spec) {
		return new AndSpecification($this, $spec);
	}
	public function _or(Specification $spec) {
		return new OrSpecification($this, $spec);
	}
	public function _not() {
		return new NotSpecification($this);
	}
}

class AndSpecification extends AbstractSpecification {
	private $spec1, $spec2;
	public function __construct(Specification $spec1, Specification $spec2) {
		$this->spec1 = $spec1;
		$this->spec2 = $spec2;
	}
	public function isSatisfiedBy($obj) {
		return $this->spec1->isSatisfiedBy($obj) &#038;&#038; $this->spec2->isSatisfiedBy($obj);
	}
}

class OrSpecification extends AbstractSpecification {
	private $spec1, $spec2;
	public function __construct(Specification $spec1, Specification $spec2) {
		$this->spec1 = $spec1;
		$this->spec2 = $spec2;
	}
	public function isSatisfiedBy($obj) {
		return $this->spec1->isSatisfiedBy($obj) || $this->spec2->isSatisfiedBy($obj);
	}
}

class NotSpecification extends AbstractSpecification {
	private $spec;
	public function __construct(Specification $spec) {
		$this->spec = $spec;
	}
	public function isSatisfiedBy($obj) {
		return !$this->spec->isSatisfiedBy($obj);
	}
}
</pre>
<pre name="code" class="php">
/**
* Cookie object just a container for the relevant data.
*
*/
class Cookie {
	protected $name,$flavor,$size;
	public function __construct($name=”,$flavor=‘chocolate’,$size=100) {
	$this->name=$name;
	$this->flavor = $flavor;
	$this->size = abs($size); // avoid negative size
	}
	public function getName() { return $this->name; }
	public function getFlavor() { return $this->flavor; }
	public function getSize() { return $this->size; }
}
/**
* Cookie service delivers cookies, offers some ways to select specific types of cookies
*
*/
class CookieService {
	protected $cookies = array();
	/**
	* Add a cookie to the collection
	* name is used as identifier, thats not the best choice
	* but it’s ok for the example
	*
	* @param Cookie $cookie
	*/
	public function add(Cookie $cookie) {
		$this->cookies[$cookie->getName()]=$cookie;
	}
	/**
	* Generic method to check which objects fit the spec
	*
	* @param Specification $spec
	*/
	private function filter(Specification $spec) {
		$result=array();
		reset($this->cookies);
		foreach($this->cookies as $name=>$cookie) {
			if($spec->isSatisfiedBy($cookie)) {
				$result[]=$cookie;
			}
		}
		return $result;
	}

	public function getLargeCookies() {
		$spec = new SmallCookieSpecification();
		$spec = $spec->_not();
		return $this->filter($spec);
	}
	public function getSmallChocolateCookies() {
		$spec = new SmallCookieSpecification();
		$spec = $spec->_and(new ChocolateCookieSpecification());
		return $this->filter($spec);
	}
	public function loadDummyData() {
		$this->add(new Cookie(‘Granny\’s classic’,‘chocolate’,60));
		$this->add(new Cookie(‘Modern Jumbo’,‘moca,chocolate’,180));
		$this->add(new Cookie(‘Kitchen Sink’,‘macadamia,cranberrie’,90));
		$this->add(new Cookie(‘Vanilla Cloud’,‘vanilla’,120));
		$this->add(new Cookie(‘Chocolate chip’,‘coconut,chocolate’,160));
	}
}

class SmallCookieSpecification extends AbstractSpecification {
	public function isSatisfiedBy($obj) {
		return $obj->getSize() < 100;
	}
}

class ChocolateCookieSpecification extends AbstractSpecification {
	public function isSatisfiedBy($obj) {
		return stristr(strtolower($obj->getFlavor()),‘chocolate’) !== FALSE;
	}
}

/**
* Client code
*/
$service = new CookieService();
$service->loadDummyData();
echo ‘
<pre>’;
var_dump($service->getLargeCookies());
var_dump($service->getSmallChocolateCookies());
echo ‘</pre>
<p>’;
</pre>
<p><a href="http://martinfowler.com/apsupp/spec.pdf">more information by E.Evans and M.Fowler</a></p>
<p class="wp-flattr-button"></p> <p><a href="http://blog.tolleiv.de/?flattrss_redirect&amp;id=560&amp;md5=8f5e5458c958ce35bf365f137221527d" title="Flattr" target="_blank"><img src="http://blog.tolleiv.de/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.tolleiv.de/2008/05/specification-ddd/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Memento [GoF]</title>
		<link>http://blog.tolleiv.de/2008/05/memento-gof/</link>
		<comments>http://blog.tolleiv.de/2008/05/memento-gof/#comments</comments>
		<pubDate>Tue, 13 May 2008 07:59:00 +0000</pubDate>
		<dc:creator>tolleiv</dc:creator>
				<category><![CDATA[behavioral]]></category>
		<category><![CDATA[memento]]></category>
		<category><![CDATA[pattern]]></category>

		<guid isPermaLink="false">http://blog.tolleiv.de/2008/05/memento-gof/</guid>
		<description><![CDATA[Let's say you got a cookie from a repository your granny and you're not sure if you like the new taste. Wouldn't it be cool if you could just try it and revoke the operation first bite if you don't like it?

In the world of OOP thats a easy job which can be handled ...]]></description>
			<content:encoded><![CDATA[<p>Let&#8217;s say you got a cookie from </span><span style="font-family: trebuchet ms; font-size: 85%;"><span style="text-decoration: line-through;">a repository</span></span><span style="font-family: trebuchet ms; font-size: 85%;"> your granny and you&#8217;re not sure if you like the new taste. Wouldn&#8217;t it be cool if you could just try it and revoke the <span style="text-decoration: line-through;">operation</span> first bite if you don&#8217;t like it?</p>
<p>In the world of OOP thats a easy job which can be handled by the so called memento pattern &#8211; you just save the inner state of the object  within a memento object and revoke you actions whenever you like&#8230;</p>
<p>As UML the example looks like this:<br />
<a href="http://bp2.blogger.com/_l5fIZzJyYfc/SClV6dPibdI/AAAAAAAAABA/bFyT-BEsqrU/s1600-h/memento-pattern.png" onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" rel="lightbox[559]"><img id="BLOGGER_PHOTO_ID_5199781707546521042" style="cursor: pointer;" src="http://bp2.blogger.com/_l5fIZzJyYfc/SClV6dPibdI/AAAAAAAAABA/bFyT-BEsqrU/s400/memento-pattern.png" border="0" alt="" /></a><br />
<a onclick="document.getElementById('codeblockMemento').style.display=((document.getElementById('codeblockMemento').style.display=='block')?'none':'block');" href="#codeMemento">Show PHP Source Code</a></p>
<pre name="code" class="php">
class CookieMemento {
    protected $flavor,$size;
    public function __construct($flavor,$size=100) {
        $this->flavor=$flavor;
        $this->size=$size;
    }
    public function getMemento() {
        return new CookieMemento($this->flavor,$this->size);
    }
    public function setMemento(CookieMemento $memento) {
        $this->flavor=$memento->flavor;
        $this->size=$memento->size;
    }
}

class Cookie extends CookieMemento {

    public function eat($reduceValue) {
        $this->size-=($reduceValue>$this->size)?$this->size:$reduceValue;
    }    

    public function printStatus() {
        echo ‘This cookie is a ’.$this->flavor.‘ cookie which has a size of ’.$this->size.‘.<br/>’;
    }
}

class Client {
    public function run() {
        $theCookie = new Cookie(‘chocolate’,100);
        $theMemento = $theCookie->getMemento();
        echo $theCookie->printStatus();
        $theCookie->eat(50);
        echo $theCookie->printStatus();
        $theCookie->eat(50);
        echo $theCookie->printStatus();
        echo ‘Hm I\’d like to eat it again …. *grin*<br/>’;
        $theCookie->setMemento($theMemento);
        echo $theCookie->printStatus();
        echo ‘ *biggrin* ’;
    }
}

$cookieMonster = new Client();
$cookieMonster->run();
</pre>
<p class="wp-flattr-button"></p> <p><a href="http://blog.tolleiv.de/?flattrss_redirect&amp;id=559&amp;md5=9baecebbe03a2d7a7f640ff56a537219" title="Flattr" target="_blank"><img src="http://blog.tolleiv.de/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.tolleiv.de/2008/05/memento-gof/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Decorator [GoF]</title>
		<link>http://blog.tolleiv.de/2008/05/decorator-gof/</link>
		<comments>http://blog.tolleiv.de/2008/05/decorator-gof/#comments</comments>
		<pubDate>Mon, 12 May 2008 22:59:00 +0000</pubDate>
		<dc:creator>tolleiv</dc:creator>
				<category><![CDATA[pattern]]></category>
		<category><![CDATA[prototype]]></category>
		<category><![CDATA[structural]]></category>

		<guid isPermaLink="false">http://blog.tolleiv.de/2008/05/decorator-gof/</guid>
		<description><![CDATA[As the first pattern I'd like to introduce the decorator pattern - it's one of the - structural patterns. It enables to extend the functionality of a existing method by wrapping a so called decorator-object.

So maybe you already know the situation ;) , your granny  is going to bake cookies and you think ...]]></description>
			<content:encoded><![CDATA[<p>As the first pattern I&#8217;d like to introduce the decorator pattern &#8211; it&#8217;s one of the [GoF]- structural patterns. It enables to extend the functionality of a existing method by wrapping a so called decorator-object.</p>
<p>So maybe you already know the situation <img src='http://blog.tolleiv.de/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  , your granny  is going to bake cookies and you think of how they gonna taste &#8211; so cookie is our <span style="font-style: italic;">main-object</span> and the different additional spices and other options which refine the taste of the cookies are the <span style="font-style: italic;">decoration</span> for it. The cookies, pardon <span style="font-style: italic;">main-objects</span>, are fine without the <span style="font-style: italic;">decoration</span> but they&#8217;re much better with and the best thing is that you&#8217;re able to combine the <span style="font-style: italic;">decorations</span>&#8230; yummy</p>
<p>So that&#8217;s how this would look like more technically:<br />
<a href="http://bp2.blogger.com/_l5fIZzJyYfc/SCjU0tPibZI/AAAAAAAAAAU/uuR_geevSdw/s1600-h/decorator-pattern.png" onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" rel="lightbox[558]"><img id="BLOGGER_PHOTO_ID_5199639771762290066" style="cursor: pointer;" src="http://bp2.blogger.com/_l5fIZzJyYfc/SCjU0tPibZI/AAAAAAAAAAU/uuR_geevSdw/s400/decorator-pattern.png" border="0" alt="" /></a></p>
<pre name="code" class="php">
stract class Cookie {
    protected $flavor;
    public function __construct($flavor) {
        $this->flavor=$flavor;
    }
    abstract public function descripeFlavor();
}

class GrannysCookie extends Cookie {
    public function descripeFlavor() {
        echo ‘<br/>Granny baked a cookie which has a taste of ’;
        echo $this->flavor;
    }
}

abstract class CookieDecorator extends Cookie {
    protected $cookie;
    public function __construct(Cookie $cookie) {
        $this->cookie = $cookie;
    }
    //abstract public function descripeFlavor();
}

class FreshCookieDecorator extends CookieDecorator {
    public function descripeFlavor() {
        $this->cookie->descripeFlavor();
        echo ‘ which smells fresh from the oven’;
    }
}

class CrumbleCookieDecorator extends CookieDecorator {
    public function descripeFlavor() {
        $this->cookie->descripeFlavor();
        echo ‘ it has tasty crumbles ’;
    }
}

$cookie = new GrannysCookie(‘chocolate’);
$cookie->descripeFlavor();

$crumbleCookie = new CrumbleCookieDecorator($cookie);
$crumbleCookie->descripeFlavor();

$freshCookie = new FreshCookieDecorator($cookie);
$freshCookie->descripeFlavor();

$freshAndCrumbledCookie = new FreshCookieDecorator($crumbleCookie);
$freshAndCrumbledCookie->descripeFlavor();
</pre>
<p><a href="http://en.wikipedia.org/wiki/Decorator_pattern">additional Information</a></p>
<p class="wp-flattr-button"></p> <p><a href="http://blog.tolleiv.de/?flattrss_redirect&amp;id=558&amp;md5=bdbadaae7a469f4d3259bb4bf3635d85" title="Flattr" target="_blank"><img src="http://blog.tolleiv.de/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.tolleiv.de/2008/05/decorator-gof/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

