<?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>Christian Grobmeier - JEE, EAI, PHP &#187; Design Patterns</title>
	<atom:link href="http://www.grobmeier.de/tag/design-patterns/feed" rel="self" type="application/rss+xml" />
	<link>http://www.grobmeier.de</link>
	<description>A Blog about technical thoughts</description>
	<lastBuildDate>Wed, 02 Jun 2010 12:32:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>The Singleton issue &#8211; an everlasting discussion</title>
		<link>http://www.grobmeier.de/2009/05/01/the-singleton-issue-an-everlasting-discussion.html</link>
		<comments>http://www.grobmeier.de/2009/05/01/the-singleton-issue-an-everlasting-discussion.html#comments</comments>
		<pubDate>Thu, 30 Apr 2009 22:01:38 +0000</pubDate>
		<dc:creator>Christian Grobmeier</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://blog.grobmeier.de/?p=208</guid>
		<description><![CDATA[Drawbacks and Benefits of the Singleton Pattern. How to implement it in PHP and in Java.]]></description>
			<content:encoded><![CDATA[<p>Today it looks that everybody needs an very extreme opinion in each technical topic. I mean, Windows is evil, OS X too, but Linux is uncomfortable and Unix is dead. JavaScript is just a toy, without JavaScript you don&#8217;t have a professional website. Java is slowest, Java is coolest and so on and so on. Finally: Singletons are evil. By the way, sometimes several people say that using design patterns destroy the ability of thinking yourself.</p>
<p>In fact, I strongly believe that every concept (ok, most <img src='http://www.grobmeier.de/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> ) have benefits and drawbacks. The case of the singleton for me is easy: it depends.</p>
<p>So what&#8217;s wrong with that pattern?</p>
<p>Some people claim that the Singleton pattern is a sign of bad software design. They say the Singleton can be used as some kind of global variable. Well, that&#8217;s true, sometimes. But the Singleton can be used otherwise than a global variable holder. Actually you have to differ between your programming language before thinking about a good or bad usage of the Singleton Pattern.</p>
<h2>How to implement the Singleton pattern in PHP</h2>
<p>PHP is a scripting language, it&#8217;s actions are performed by an interpreter. It doesn&#8217;t support multiple threads like Java or Ruby does. This is very important later. But first, lets create a singleton in PHP.</p>
<pre>class MySingleton {</pre>
<pre>    private static $instance;</pre>
<pre>    private function __construct() {}</pre>
<pre>    public static function getInstance() {</pre>
<pre>        if(self::instance == null) {</pre>
<pre>            self::instance = new MySingleton();</pre>
<pre>        }</pre>
<pre>        return self::instance;</pre>
<pre>    }</pre>
<pre>}</pre>
<p>How does this work? You create a static variable in a class. If one calls getInstance() for the first time, a new object is created and stored in the static variable. If you call the method again, you&#8217;ll get exactly the same instance you created with the first call. This object &#8211; since it is static &#8211; will stay until your script has ended and the complete request is processed. You see, why the singleton has it&#8217;s name. It&#8217;s only one object created and used for all the time.</p>
<p>And to keep this behaviour, you just have to put your constructor private &#8211; nobody else than your getInstance method should be allowed to create this object.</p>
<h2>How to implement a Singleton with Java</h2>
<p>Now you have to think about some more issues. Since Java supports multithreading you have to think about more than just creating the object and returning it. First, we&#8217;ll see how a pure PHP programmer would create the singleton with Java syntax.</p>
<pre>public class MySingleton {</pre>
<pre>    private static MySingleton instance;</pre>
<pre>    // Again - just MySingleton is allowed to construct this object</pre>
<pre>    private MySingleton() {}</pre>
<pre>    public static getInstance() {</pre>
<pre>        if(instance == null) {</pre>
<pre>            instance = new MySingleton();</pre>
<pre>        }</pre>
<pre>        return instance;</pre>
<pre>    }</pre>
<pre>}</pre>
<p>OK, now think about two threads which call getInstance() at the same time, and imagine nobody has done so before. Both threads would enter getInstance(). Chances are good that Java helps you even with multiple processors (it should do, cause Suns Sales Managers sell Java as a simple to use language <img src='http://www.grobmeier.de/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> ). In that case, one thread would go on to create the MySingleton object, while the other one will jump over it and return the instance.</p>
<p>You have to ask the question, does this really work? Cause at which point of time is instance not longer null? The answer is, if you create the object headers, the instance variable is not longer null. That means, that a second thread could overtake thread one and work on an instance which is not really created (just the have of it)! Something unexpected will occure and even if your customer will claim about an error, you probably will never have the chance to find it.</p>
<p>So what now? We have to make sure that:</p>
<p>a) two threads are not creating a MySingleton object at the same time<br />
b) one thread doesn&#8217;t work on the object while it is still under construction</p>
<p>Some programmers start something like this:</p>
<pre>public class MySingleton {</pre>
<pre>    private static MySingleton instance;</pre>
<pre>    public static getInstance() {</pre>
<pre>        if(instance == null) {</pre>
<pre>            synchronized(this) {</pre>
<pre>                if(instance == null) {</pre>
<pre>                    instance = new MySingleton();</pre>
<pre>                }</pre>
<pre>            }</pre>
<pre>        }</pre>
<pre>        return instance;</pre>
<pre>    }</pre>
<pre>}</pre>
<p>Please note the synchronized block above. It keeps care that only one thread can execute the code for creation at one time.</p>
<p>Is this the solution? No. Even in that case it can happen that Thread 1 locks everything correctly for creating the object. But if Thread 2 comes at a bad time, it will ask the outer instance == null check and again it could return an unfinished object. The synchronized block just helps with one problem.</p>
<p>Actually there is only one 100% solution. Create the necessary object while class loading.</p>
<pre>public class MySingleton {</pre>
<pre>    private static MySingleton instance = new MySingleton();</pre>
<pre>    public static getInstance() {</pre>
<pre>        return instance;</pre>
<pre>    }</pre>
<pre>}</pre>
<p>This is a solution PHP programmers cannot have since PHP doesn&#8217;t support to create objects like this. But for the Java programmer it&#8217;s the only way to make object creation work. And yes, sometimes it&#8217;s not possible to go this way. But that&#8217;s another story.</p>
<h2>Singleton Lifetime</h2>
<p>You should know about another difference between Java and PHP Singletons. In Java, the static keywords makes the variable available at a class level, not at object level. This means it follows you as long as the JVM is alive &#8211; from programm start to programm end, and in case of an enterprise or an eai server, this can take a long, long time.</p>
<p>For a PHP programm it&#8217;s the same &#8211; from programm start to programm end. But in PHP words this means the time when an HTTP request arrives and script execution begins till the end of the script has been reached. After a request, the singleton is gone, dead, and you&#8217;ll have to create it again, with the next request.</p>
<p>In human words, this means that a Java singleton probably lives for days, weeks or even months and the PHP singleton just for less milliseconds.</p>
<h2>The Benefits of Singleton</h2>
<p>Well, benefit is: you have to create only one object of an class and can use it over and over again. This is cool, since creating an object takes usually a long time in the interpreter or in the virtual machine. Cause of this, old programmers often say object orientation is slow. Meanwhile everything is faster and in most cases you don&#8217;t have to care bout this anymore.<br />
And this is where critic starts: people say, you could misuse the Singleton as some kind of global variable store. This comes often from PHP programmers, who think about that code:</p>
<pre>class MySingleton {</pre>
<pre>    ...</pre>
<pre>    public $bla = "blubber";</pre>
<pre>    public static function getInstance() {</pre>
<pre>        ...</pre>
<pre>    }</pre>
<pre>}</pre>
<p>In this case, you can have the variable $bla available all over your code. Just do a:</p>
<pre>MySingleton::getInstance()-&gt;$bla;</pre>
<p>Is this good? No. Of course not. If you just want to store something, go ahead, use $GLOBALS or a similar global available variable. Same goes to Java. There are no global fields, but you can create some similar with System properties.</p>
<p>But Singleton will have more the worth if the singleton object has some methods you can operate on. Imagine that singleton object trys to reload a configuration.</p>
<pre>class MySingleton {</pre>
<pre>    ...</pre>
<pre>    public $bla = "blubber";</pre>
<pre>    public function loadConfiguration() {</pre>
<pre>        // code to load xml file</pre>
<pre>        $this-&gt;bla = getValueFromXML();</pre>
<pre>    }</pre>
<pre>    ...</pre>
<pre>}</pre>
<p>This would make it possible to reload the config at runtime. Even date formatting etc. would be possible at runtime.</p>
<p>Basically said, an object which provides methods is worth something. It&#8217;s not to bad to do so. But a more cool benefit is if you have a stateless singleton.</p>
<pre>class MySingleton {</pre>
<pre>    ...</pre>
<pre>    public function doSomething($bla) {</pre>
<pre>        $bla = $bla / 2;</pre>
<pre>        return $bla;</pre>
<pre>    }</pre>
<pre>    ...</pre>
<pre>}</pre>
<p>Imagine doSomething() does some complex things with $bla. You don&#8217;t need to store the result in the MySingleton object. It will returned. Since there are no object variables available, this object is stateless. And there is really no need to create multiple objects just to perform some operations on $bla.</p>
<p>But why should one consider to create an object if he can do this in a static way, you ask. Static access to methods is not very flexible. Think on AOP, where objects wrap other objects and prevent you from calling a method directly. This wouldn&#8217;t work. That&#8217;s just one example. There are others: maybe you want to choose at runtime, which implementation you use to create this task. In a static context you would have to change your implementation, in an object context you could use a factory and a strategy pattern to switch. This is way more flexible.</p>
<h2>Drawbacks of the Singleton pattern</h2>
<p>Yes, of course there are several. Think on the global variable thing. It&#8217;s true, imagine you have one thousand of Singletons, all keeping care of their own little states, read within the application from a million of places. Not very good. Esspecially with PHP you cannot easily find out where those variables are called. In Java you have some good shortcuts in your IDE.</p>
<p>But we know now, that a Singleton is meant for reducing object creation time and not for state sharing. Next drawback is more significant, since the first one is a mistake just inexperienced programmers do.</p>
<p>Problem is, if you create a Singleton it will stay one forever. If you need to make multiple objects of your class, you have to write code for this. In small projects this is not such a big issue, but in a 100.000 lines of code project it is. There are other patterns like Prototype or Factory which could be useful suddenly and we would have to write code. This is a risk.</p>
<p>The solution is to create this Singleton not by code like we did above. Use a framework for creating your objects. In PHP you PIWI and the BeanFactory at your side, which helps you with constructing singletons (and injects the objects in other objects &#8211; Dependency Injection, see the previous article).<br />
In Java you can use Spring for this. Spring is the big inspiration source for PIWI (regarding object creation and dependency injection) and widely used. Besides Spring there is Google Guice and PicoContainer too, which provide similar stuff.</p>
<h2>Finally</h2>
<p>There is no need to say Singleton is good or bad. It&#8217;s neither. It&#8217;s just a pattern. A Singleton is just as evil as you misuse it, and just as glorious as you identify it as fitting pattern to a specific problem.</p>
<p>In my projects I use a Singletons sometimes for configuration. I don&#8217;t think it&#8217;s bad behaviour. If I don&#8217;t have one thousand of this object in my System, it&#8217;s OK. More often Singletons are used as some kind of worker classes, just here for doing complex stuff with storing a state. They help me not to waste memory. And due Singletons are objects I easily can extends them via aspect oriented programming &#8211; perfect!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.grobmeier.de/2009/05/01/the-singleton-issue-an-everlasting-discussion.html/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Dependency Injection &#8211; a Design Pattern</title>
		<link>http://www.grobmeier.de/2009/04/16/dependency-injection-a-design-pattern.html</link>
		<comments>http://www.grobmeier.de/2009/04/16/dependency-injection-a-design-pattern.html#comments</comments>
		<pubDate>Thu, 16 Apr 2009 10:49:50 +0000</pubDate>
		<dc:creator>Christian Grobmeier</dc:creator>
				<category><![CDATA[Open Source]]></category>
		<category><![CDATA[PIWI]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://blog.grobmeier.de/?p=196</guid>
		<description><![CDATA[What is the dependency injection design pattern? Here are examples in PHP. Explained on PIWI and Spring Framework.]]></description>
			<content:encoded><![CDATA[<p>Design Patterns are useful and a must have. Everybody working seriously on software projects should know about them. End of 2007 I decided to use the powerful Spring Framework at my new enterprise project.  The project, which ended these days for me, was a huge success. We made complex changes easy, had very good unit testing and all that stuff. We had up to 12 developers working on the code, I am really thinking that Spring did lots for our success. It was so easy to seperate all the modules and integrate new features within minutes. I am writing this in my article about Dependency Injection, cause Spring highly depends on this design pattern and PIWI will do that, too.</p>
<h2>Design Patterns &#8211; all just theory?</h2>
<p>If students make their exams and come as junior programmers to my projects, they often believe a design pattern is something to eat. Or something theoretical. Or simply a joke. I usually start with explaining how to use it and such, but at the first glance it seems to abstract to them. Later, with the expierence, comes the joy.</p>
<p>This is true for patterns like Singleton or Factory or maybe Model-View-Controller. Coming to Dependency Injection &#8211; which is not read very often in Books about good software design &#8211; most people NEVER have joy. In this kind it behaves like the Proxy pattern. One really cannot use this out of the box. I mean, a singleton can be implemented within minutes, and it does what it does. But Dependency Injection? It&#8217;s more a concept of software design than a design pattern. Can you implement a singleton? Yes. Can you implement Dependency Injection? No, of course not. Having that said, the joy and the power comes when you are using a fitting framework which supports the design pattern. Like Spring. Or PIWI, in the latest trunk version. Cause we PIWI-folks simply have stolen much of the ideas of Spring and now use it not only in Java, but in PHP5 too.</p>
<h2>What&#8217;s all about it?</h2>
<p>Basically Dependency Injection simply says: don&#8217;t make a class dependent from another, inject the dependency. So what? some will say. But it&#8217;s simple. Imagine the following PHP lines:</p>
<pre>class Car {
   private $driver = null;

   public crash() {
      $this-&gt;driver-&gt;saySomething();
   }
}</pre>
<p>You see, there is a private member called driver in the car class. If your use case is that each car is a driver, it&#8217;s quite easy in most cases. Just fill the member in the constructor. This is, what most people do. This makes $driver nullsafe.</p>
<pre>class Car {
   private $driver = null;

   public __construct() {
      $this-&gt;driver = new Driver();
   }

   public crash() {
      $this-&gt;driver-&gt;saySomething();
   }
}</pre>
<p>OK. From this point on the class Car depends on the class Driver, cause you need the Driver class to instanciate Car. After you did that and all works well, your boss looks round the corner and tells you that we need to distinguish between female drivers and male drivers. He is sorry for saying that so late, but it&#8217;s like this. Cause if you call the new method crash(), a female driver would simply say:&#8221;you crashed me!&#8221; and a male driver would say something like:&#8221;guy i have a gun!&#8221;. And, that&#8217;s the point, your client A just wants male drivers in their systems, while client B just needs female drivers.</p>
<p>People start doing:</p>
<pre>class Car {
   private $driver = null;

   public __construct($client) {
      if($client == "A") {
         $this-&gt;driver = new MaleDriver();
      } else if($client == "B") {
         $this-&gt;driver = new FemaleDriver();
      }
}

   public crash() {
      $this-&gt;driver-&gt;saySomething();
   }
}</pre>
<p>All is good. But what if you need to port the system for somebody who just let childs drive? Or people with glasses upon their noses? In fact, we had the requirement to create several modules for several clients &#8211; customization. Yes, the example above with male and female drivers is not the best, but I am sitting in a car while typing this.</p>
<p>Problem on the approach above is that you need a new if else if you ever have more Driver types than above. And you have to put this in class where such dependencies exist. Maybe it&#8217;s not pretty much, but in our case we had about 20 modules &#8211; without customizations. I really was afraid before such a switch.</p>
<h2>Dependency Injection for the solution</h2>
<p>As I allready told you, we had Spring and Java 6 in our system. But we ported dependency injection to PIWI. And if you are using one of these frameworks, you know that both heavily use XML. Imagine you could say in an XML which driver you want to use. More better: you really would define an interface for all the driver classes and would make sure that you operate on that interface only.</p>
<p>See this:</p>
<pre>interface Driver {
   public saySomething();
}

class FemaleDriver implements Driver {
   public saySomething() {
      echo "You crashed me!";
   }
}</pre>
<p>(imagine something similar for MaleDriver).</p>
<p>You could do something like that:</p>
<pre>class Car {
   private $driver = null;

   public __construct($driver) {
      $this-&gt;driver = $driver;
   }

   public crash() {
      $this-&gt;driver-&gt;saySomething();
   }
}</pre>
<p>Isn&#8217;t your code much cleaner now? You know, if else means death to object orientation! This way your Car class doesn&#8217;t depend to MaleDriver or FemaleDriver. In case of PHP5 it just depends on an untyped object. In case of Java it depends on the Interface Driver.</p>
<p>By the way: you can force types in PHP5 (in some level of course). You could write the constructor like this:</p>
<pre>public __construct(Driver $driver) {
   $this-&gt;driver = $driver;
}</pre>
<p>This forces the caller to put an object inside which implements the interface Driver. And this in fact is the way you should go! And this is all about the Dependency Injection pattern. It says, make your classes dependend on interfaces, not on classes.</p>
<p>So, isn&#8217;t it nice? But how do you decide to bring your dependency in? This is another point, and this is why I said you have to check out Spring or PIWI for this. The example above is working gorgeous, but if you don&#8217;t find a mechanism to bring your dependencies into the game, all is lost. I promised XML like Spring does, and here it is: PIWIs XML file for Dependency Injection in PHP.</p>
<pre>&lt;bean id="xmlPage" class="XMLPage" scope="request"&gt;
   &lt;property name="contentPath" php="$GLOBALS['PIWI_ROOT'].CONTENT_PATH" /&gt;
   &lt;property name="siteFilename" value="site.xml" /&gt;
&lt;/bean&gt;

&lt;bean id="siteSelector" class="SiteSelector" scope="request"&gt;
   &lt;property name="page" ref="xmlPage" /&gt;
&lt;/bean&gt;</pre>
<p>We call our objects beans, like Spring does. It&#8217;s Spring-Beans in Spring, but PIWI-Beans in PIWI. We are shameless. First, look at the bean definition with the id xmlPage. You give it a class and a scope, and some properties.</p>
<p>Basically, PIWI (and Spring too) creates the objects for you. That has many benefits. I will write an blog article why instanciating objects yourself is sometimes a bad idea some day. However, PIWI makes an object and stores it in our context, the BeanFactory. It&#8217;s stored under the id xmlPage, and you can get the object manually if you call:</p>
<pre>$xmlPage = BeanFactory::getBeanById('xmlPage');</pre>
<p>This brings you the ready bean. Additionally you tell the BeanFactory that it should set the property &#8220;siteFilename&#8221; to &#8220;site.xml&#8221;. And one line above you even give it an PHP expression. After PIWi made the object from the class XMLPage, it checks if a member variable is accessible named siteFilename. If it isn&#8217;t it looks if there is a method called setSiteFilename($o); or siteFileName($o). If PIWI found that method, it calls it with the value.</p>
<p>This is all done by reflection, which has been shipped with PHP5. No dependencies to other libs, no problem. Just plain PHP5. Same goes to Java. Plain Java. No Magic. Just some reflection.</p>
<p>If you would have called this line instead of the one above:</p>
<pre>$siteSelector = BeanFactory::getBeanById('siteSelector');</pre>
<p>the BeanFactory would have created the siteSelector bean. If you look into it, you see this:</p>
<pre>&lt;property name="page" ref="xmlPage" /&gt;</pre>
<p>If the BeanFactory gets aware of this (and it does!), it will look in the context for a PIWI Bean with the ID xmlPage. If there isn&#8217;t one, it will try to create such a bean. Same rules as above. After creation of xmlPage it will be set into SiteSelector&#8217;s setPage($xmlPage) method.</p>
<p>And now imagine how your boss would love it, if you tell him that such a customization is just a matter of some XML?</p>
<pre>&lt;bean id="maleDriver" class="MaleDriver" scope="request" /&gt;
&lt;bean id="femaleDriver" class="FemaleDriver" scope="request" /&gt;

&lt;bean id="car" class="Car" scope="request"&gt;
   &lt;property name="driver" ref="maleDriver" /&gt;
&lt;/bean&gt;</pre>
<p>Everthing done!</p>
<p>For the sake of completness &#8211; what do we mean with scope? Well, scope is in which scope your object lives. Defining request means, the we create maleDriver only once while the whole request. If you define another class which needs maleDriver, it would get &#8211; exactly the same -. This is, what some people call a Singleton in PHP. But Singletons are worth an own Blog entry, since some people &#8211; esspecially who have just written code with PHP and not for Java Enterprise Systems &#8211; say, Singletons are evil. Well, they are not. If developers are not thinking while coding, that is evil <img src='http://www.grobmeier.de/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' />  You can misuse everything, if you want to.</p>
<p>Here is another example for using the driver more than once:</p>
<pre>&lt;bean id="maleDriver" class="MaleDriver" scope="request" /&gt;
&lt;bean id="femaleDriver" class="FemaleDriver" scope="request" /&gt;

&lt;bean id="car" class="Car" scope="request"&gt;
   &lt;property name="driver" ref="maleDriver" /&gt;
&lt;/bean&gt;

&lt;bean id="truck" class="Truck" scope="request"&gt;
   &lt;property name="driver" ref="maleDriver" /&gt;
&lt;/bean&gt;</pre>
<p>In this case, only the same instance of maleDriver makes it to the truck and to the car. Decide yourself if this is your usecase. In the MaleDriver class are no states defined &#8211; so one object is enough.</p>
<p>OK &#8211; Dependencies are out. Instanciation is out of the code too. But is this the whole benefit? Not really. This stuff makes it possible to create dynamic proxies and use aspect orientation, even with PHP. And be sure, PIWI will have features some day. And Spring still got this cool stuff. But that&#8217;s another story.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.grobmeier.de/2009/04/16/dependency-injection-a-design-pattern.html/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
