Archive for April, 2009

Switching workspaces with Eclipse Ganymede

Monday, April 27th, 2009

Due to a new external harddrive, I needed to switch my workspace from one disk to another. Eclipse Ganymede under OS X 10.4 doesn’t reckon the switch correctly if you deleted your old workspace from your old harddisk completly. For example, I moved my stuff from harddisk FELIX to harddisk ANDREW and deleted the workspace on FELIX. Eclipse failed to ask me where the workspace dissappeared, since I once said that Eclipse shouldn’t ask me again. And then it closes, without even showing the error message more than 3 seconds. Well. Bad. :-)

Solution is to edit the following file:

$ vi configuration/.settings/org.eclipse.ui.ide.prefs

Just switch:

SHOW_WORKSPACE_SELECTION_DIALOG=false

to:

SHOW_WORKSPACE_SELECTION_DIALOG=true

and the workspace selection dialog should appear again. This gives you the option to choose another workspace.

Committing to Log4PHP

Monday, April 27th, 2009

I just was off for a weekend to celebrate the wedding of good friends – and after returning I found myself beeing committer to Log4PHP. Well, OK, I wasn’t surprised since Gavin and I tried for over a month to get access to this repository. Finally we made it. :-)

Log4PHP is an api for logging within PHP applications. As the name suggests, it’s a port from Log4J which is todays standard in Java applications. Log4PHP has had several attempts to get running, but always went dry. It was february 2007 where lads kicked off the project again.

However, since I need this  Log4PHP as a dependency on PIWI I really don’t want to let it go. It has so much benefits to PIWI. And finally I don’t know a better logging tool than Log4J or its port Log4PHP is. Beside that Log4PHP is a great api, I think it will help to get PHP developers more attracted to Apache. This is important since there are so less PHP guys here. Apache Incubator Shindig is the only project I know with a regular contribution for PHP. Well, hopefully we get a community back the next days and hopefully some of those users turn into fullfledget committers too. We’ll see.

It’s some stuff todo. Nothing critical, just some design issues, small errors and some todos. I guess, we can work on a 1.0 once those issues are resolved. We’ll see :-)

Here are some links for further reading:

http://incubator.apache.org/log4php/

https://issues.apache.org/jira/browse/LOG4PHP

http://incubator.apache.org/projects/log4php.html

Dependency Injection – a Design Pattern

Thursday, April 16th, 2009

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.

Design Patterns – all just theory?

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.

This is true for patterns like Singleton or Factory or maybe Model-View-Controller. Coming to Dependency Injection – which is not read very often in Books about good software design – 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’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.

What’s all about it?

Basically Dependency Injection simply says: don’t make a class dependent from another, inject the dependency. So what? some will say. But it’s simple. Imagine the following PHP lines:

class Car {
   private $driver = null;

   public crash() {
      $this->driver->saySomething();
   }
}

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’s quite easy in most cases. Just fill the member in the constructor. This is, what most people do. This makes $driver nullsafe.

class Car {
   private $driver = null;

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

   public crash() {
      $this->driver->saySomething();
   }
}

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’s like this. Cause if you call the new method crash(), a female driver would simply say:”you crashed me!” and a male driver would say something like:”guy i have a gun!”. And, that’s the point, your client A just wants male drivers in their systems, while client B just needs female drivers.

People start doing:

class Car {
   private $driver = null;

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

   public crash() {
      $this->driver->saySomething();
   }
}

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 – customization. Yes, the example above with male and female drivers is not the best, but I am sitting in a car while typing this.

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’s not pretty much, but in our case we had about 20 modules – without customizations. I really was afraid before such a switch.

Dependency Injection for the solution

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.

See this:

interface Driver {
   public saySomething();
}

class FemaleDriver implements Driver {
   public saySomething() {
      echo "You crashed me!";
   }
}

(imagine something similar for MaleDriver).

You could do something like that:

class Car {
   private $driver = null;

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

   public crash() {
      $this->driver->saySomething();
   }
}

Isn’t your code much cleaner now? You know, if else means death to object orientation! This way your Car class doesn’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.

By the way: you can force types in PHP5 (in some level of course). You could write the constructor like this:

public __construct(Driver $driver) {
   $this->driver = $driver;
}

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.

So, isn’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’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.

<bean id="xmlPage" class="XMLPage" scope="request">
   <property name="contentPath" php="$GLOBALS['PIWI_ROOT'].CONTENT_PATH" />
   <property name="siteFilename" value="site.xml" />
</bean>

<bean id="siteSelector" class="SiteSelector" scope="request">
   <property name="page" ref="xmlPage" />
</bean>

We call our objects beans, like Spring does. It’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.

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’s stored under the id xmlPage, and you can get the object manually if you call:

$xmlPage = BeanFactory::getBeanById('xmlPage');

This brings you the ready bean. Additionally you tell the BeanFactory that it should set the property “siteFilename” to “site.xml”. 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’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.

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.

If you would have called this line instead of the one above:

$siteSelector = BeanFactory::getBeanById('siteSelector');

the BeanFactory would have created the siteSelector bean. If you look into it, you see this:

<property name="page" ref="xmlPage" />

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’t one, it will try to create such a bean. Same rules as above. After creation of xmlPage it will be set into SiteSelector’s setPage($xmlPage) method.

And now imagine how your boss would love it, if you tell him that such a customization is just a matter of some XML?

<bean id="maleDriver" class="MaleDriver" scope="request" />
<bean id="femaleDriver" class="FemaleDriver" scope="request" />

<bean id="car" class="Car" scope="request">
   <property name="driver" ref="maleDriver" />
</bean>

Everthing done!

For the sake of completness – 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 – exactly the same -. This is, what some people call a Singleton in PHP. But Singletons are worth an own Blog entry, since some people – esspecially who have just written code with PHP and not for Java Enterprise Systems – say, Singletons are evil. Well, they are not. If developers are not thinking while coding, that is evil ;-) You can misuse everything, if you want to.

Here is another example for using the driver more than once:

<bean id="maleDriver" class="MaleDriver" scope="request" />
<bean id="femaleDriver" class="FemaleDriver" scope="request" />

<bean id="car" class="Car" scope="request">
   <property name="driver" ref="maleDriver" />
</bean>

<bean id="truck" class="Truck" scope="request">
   <property name="driver" ref="maleDriver" />
</bean>

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 – so one object is enough.

OK – 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’s another story.

Classloading in PHP – and how it is done in PIWI

Monday, April 13th, 2009

In PHP4 world a developer wrote scripts and included this scripts in other scripts with the wellknown include(), include_once(), require() or require_once() statements. As a PHP developer for long time I remember the pain: thousands of scripts, thousand ways to name them and tons of includes. It hasn’t become better with PHP4 first support of objectoriented programming. Actually it has gone even more worse, since a OOP developer usually uses one file per class. Again, the thousands of includes become more and more and finally we all used required_once() since we couldn’t know if another class allready included the file we want now.

Addionally, include (and similar, from now on I always use “include” if I refer for such kind of statements) is very static. If you want to move your class into another folder you have to search/replace some stuff. Sometimes I even found an empty file when a file has been moved, just with another include with the new location! Really, include is very bad. In the past I developed several loading mechanisms, but they always were quite hard and complex and didn’t turn on automatically.

Things changed with PHP5. There is a new magic method called __autoload(). And guess what – this method is usually called from the interpreter if you call a class which definition hasn’t been found in memory yet. We at PIWI use this new function as a core concept. Let me explain how.

Basically we don’t use any include statements anymore. They are evil and static. And of course we don’t have any procedural scripts in PIWI (except the starter file index.php). The latter one gives us the option to say:”whatever we need to be included, it must be a class or an interface”. That is the point were the __autoload function steps in. If we need a class or an interface, this method is called and our own Classloader concept is working.

To make things happen, we wrote a ClassLoader class which does the dirty work. It’s the only include statement we have. And that’s OK.

/** ClassLoader which makes other includes dispensable. */
require_once ("lib/piwi/classloader/ClassLoader.class.php");

Then we need to define the __autoload method. You should know that only one __autoload method definition is allowed per script. I would say it’s a good style if you only have one algorithm for looking up your classes per project.

Then we create the variable which holds the reference to the classloader.

/** Instance of the Classloader. */
$classloader = null;

As you may have noticed, I do this outside of the __autoload function. This is cause I don’t want to instanciate my ClassLoader each time I call the __autoload. To see how we make sure, that this variable is only filled once, we have to take a look into the __autoload method itself:

function __autoload($class) {
        global $classloader;
        if ($classloader == null) {
                $classloader = new ClassLoader($GLOBALS['PIWI_ROOT'] . 'cache/classloader.cache.xml');
        }

        $directorys = array ('lib', CUSTOM_CLASSES_PATH);

        foreach ($directorys as $directory) {
                $result = $classloader->loadClass($directory, $class);
                if ($result == true) {
                        return;
                }
        }
}

First we make $classloader global to the function. Then we check if it isn’t null. If it has been allready filled, we go on. If not, we create the ClassLoader object. You see in the above example, we are using a cache file too. Its an XML file and we put an entry into it whenever we found a location to a class.

After that we iterate about our class folders and call loadClass on each one. This method looks in the cache first. If the class is found in the cache, it is simply returned. If it’s found in the cache and the class has moved, the cache entry is deleted and normal load procedure starts. If even this fails, an error occurs.

The ClassLoader checks recursive in the parameter classfolder for the class. It loads the first file with the name of the class and if.php or class.php or even only .php (since PIWI 0.0.9) into the system. Example: if you lookup a class name MyClass, it should be in the file MyClass.class.php, MyClass.if.php or MyClass.php.

We recommend using .class.php for Classes, .if.php for Interfaces. We support .php only cause other projects may not have this convention – like log4php. Integraton is important to PIWI, since there are numberous projects outside we want to support and use ourselves.

You can easily use the ClassLoader classes yourself, even if you don’t use PIWI. Just download the PIWI package and grab the necessary classes in the ClassLoader folder.

However, there are some drawbacks of using __autoload. Reading files from the harddisk (that is what you do if you include classes) is not very performant compared to having everything in one huge file. But for the sake of readability, we always had success with putting one class per file. I never came to the point were this is really important. Additionally we have a html cache at PIWI working. This reduces waste of performance.

Second, but not really important (imho): __autoload can only load classes of course :-) Half procedural, half objectoriented is no more. If you are a traditional developer and use classes only where necessary, you probably will not have much benefits from __autoload.

Last thing to know: be rigoros with your exceptions in ClassLoader: log them (with Log4php) whereever they occur – those exception occuring in __autoload cannot be catched!

PIWI 0.0.9 released!

Sunday, April 12th, 2009

Yesterday we released PIWI at version 0.0.9 – the last of the 0.0.x series :-)

Since the first serious projects started to use PIWI, we had lots of valuable feedback for our development. Changes are:

PIWI does now logging with the great Log4PHP framework from Apache. Together with the improved exception handling people can reproduce PIWIs workflow much better than before. To be honest, for our users it was quite difficult to understand was PIWI does. Now it’s easier :-)

FormProcessing, JSONSerializer, TextSerializer now support more functions in the case of todays AJAX usage. We really were surprised what our Users did with PIWI – in fact this new implementations are the result of ongoing feedback. Thanks to all e-mail and contributions!

Additionally we have fixed lots of small issues which makes life much more easier for all PIWI users and devs.

As allready mentioned, the next release will have the version number 0.1.0. We are developing our dependency injection container and will refactor PIWIs core to make it more extensible. Dependency Injection in PIWIs case means that we try to adopt the ideas of Springs dependency injection.

JJSon: Bugfix release out and new stuff in trunk

Thursday, April 2nd, 2009

This early morning I uploaded a new JJSon version (0.0.3). It resolves the first and only issue with the lib: unfortunatly I created the jar with Java 6 bytecode. Well, my newly created POM file will prevent me for errors like this in future. From nowon JJSon is a Maven 2 project. Get the new jar at JJSon’s Googlecode page.

Motivated by the 100 downloads I started to create the Annotation encoder yesterday night. Its very basic and doesn’t contain good testcases at the moment, but at first glance it works :-) You can serialize Java Objects into a JSon string with that stuff. Supported are the usual json types, except double (sorry, forgot that). List and Maps can be serialized too, aswell as annotated pojos.

I will add the double and some more testcases in future, then try to aim to the next release. Additionally I want to release a zip file next time, containing license stuff and maybe some docs. If you are willing to help, shout!

Background info:

JJSon is a small API for working with the Json format. There are several libs out there, but I don’t know any which are well encoded AND have no dependencies. JJSon doesn’t provide all features the other libs have, but aims to be easily extendable and definitly comes without any necessary dependencies.

  • Recent Posts

  • Tags

  • Categories

  • Archives

  • Wave Notifications

    Download Adobe Wave now!

    This application requires Adobe® AIR™ to be installed for
    Mac OS or Windows.




Feeds