gooh's posterous

Feb 13

Modeling the Real World

A few days ago, I was asked by @__edorian whether I’d agree to the statement that developers model the real world. I considered the question briefly and then replied

We as Software Developers don’t model the real world, we abstract domain concepts into deterministic programs

In this blog post I’ll expand on that statement by example.

The Scenario

Let’s say you are tasked to build a Online Car Reservation System (it’s always cars in OO tutorials) for a local Car Rental Service. You meet with the client for the first time, she explains her vision to you and after a few days, she hands you the requirements for a first UseCase:

UseCase UC1: Reserve Car

Primary Actor: Website Visitor
Stakeholders and Interests: yaddayaddayadda
Preconditions: none

Success Guarantee (Postconditions):

  • Reservation is saved.
  • Rental Cost is correctly calculated.
  • Car is reserved at Rental Station
  • Reservation Voucher is sent to Website Visitor via eMail

Main Success Scenario (Basic Flow):

  • Website Visitor arrives at Website
  • Website Visitor enters Rental Date and Website Visitor’s eMail
  • System records selected Rental Date and Website Visitor’s eMail
  • System determines available cars for Rental Date
  • Website Visitor selects Car to reserve
  • System records selected Car
  • System calculates and presents Rental Cost to Website Visitor
  • System secretly sells eMail address to Affiliate Marketer
  • Website Visitor confirms Car Reservation
  • System reserves Car at Rental Station
  • System confirms Car Reservation to Website Visitor
  • System sends Reservation Voucher to Website Visitor’s eMail

Extensions (Alternate Flow): more yaddayaddayadda

Doesn’t sound too difficult. On to modeling.

Don’t model the real world

Now, let’s imagine you start to model the real world from this UseCase. What do you need? Obviously, the Car. What makes up a Car in the real world? Right, it got a motor, and tires and doors and a trunk and windows and windshield wipers and a fuel tank and an exhaust pipe and a handbrake and seats (dont forget the seats) and an AC and rear view mirrors and … are we there yet? No, because a Car has a couple thousand parts. And the vast majority of them are meaningless for your client’s Reservation System.

What you really want to model is a Car as it makes sense in the Business Domain of our client’s Car Rental Service and the purpose of the application at this stage.

Abstract Domain Concepts

So instead of wasting your time creating unneeded complexity, you just look at the UseCase. But since you are not a Rental Agent, you decide to call up the client again to get some reaffirmation about your understanding of how this is supposed to work:

You: Hi, can we talk about the UseCase once more? I’d like to make sure I understand what we are talking about before I start coding.

Client: Of course. Let me just summarize it in my own words. Our Clients can make Reservations for specific Cars at a certain Date. And they should get a Voucher for that, which they can carry to our local rental station. And that’s where we make the actual Rental.

You: Ok, about the Car, what’s important about it? Is there any particular criteria the Client can pick from when choosing the car?

Client: Not really. We only have a dozen cars. Usually we just tell the client which brand and model that is and how much it will cost to rent it. In the summer, the clients often ask whether the car has an air condition, so I guess that is important to note online, too.

You: That’s pretty simple. I thought there might be more about the Cars.

Client: We do keep track of a lot more data about our cars, but for the UseCase it’s not important. Let’s keep it at the simple level for now.

You: Got it. One last thing. Umm, do you really want to secretely sell the eMail adress of the client to an Affiliate Marketer?

Client: Haha, no. I was just checking whether you were reading the UseCase.

You: Thanks, I think I know all I need to know right now. I’ll send you a diagram in a couple minutes, visualizing what we just talked about.

UML Model for Car Reservation UseCase - powered by yuml.de

Into Deterministic Programs

Now that you know how to think in the mental model of a Rental Agent, it’s time to add your own expert knowledge. The UML above is good for communicating with your client, but it’s not a runnable program. Don’t confuse it with class diagrams. It’s just the conceptual basis.

So the next step is translating your newfound knowledge into something a computer can execute. In this phase, you will design and ultimately code the components you need in the various layers in what the UseCase only calls “the System”.

For your client, these details are largely uninteresting. Whether you use ActiveRecord or TableDateGateway as a pattern for your persistence layer, whether you use Singletons or Framework XYZ doesn’t matter to him. She trusts you to deliver a professional result.

She also likely won’t be interested in Class diagrams or similar UML artifacts. Whether you use those is up to you. What counts is that you concentrate on modeling your client’s view of their problem domain in a way that allows you and him to communicate and you to build a software system around it.

And that’s what my initial statement means.

Oct 30

Why the PSR-0 Classloader does not belong into SPL

There is currently an RFC in the PHP Wiki proposed by the PSR Standards Group about including a classloader into SPL that will autoload classes following the PSR-0 File and Class naming convention.

In case you dont know what the PSR Group is, here is some background

In the mid of 2009, several lead developers started an initiative called PHP Standards Group (aka. Framework Interoperability Group), which is mainly focused on interoperability between different Open Source projects.

Let’s not discuss whether it was a good idea to adopt the name PHP Standards Working Group although they are not in the position to define anything official for PHP at all. Rather, let’s discuss whether we want to add code to native PHP that requires a developer to adopt a certain code convention. The term convention is important here, because that’s what PSR-0 is. It is not a standard, but a convention; followed by a certain interest group connected by a certain need: framework interoperability.

Framework interoperability is a reasonable goal. Being able to painlessly plug Doctrine into Symfony and add ZF on top will surely make the lifes of those that need such setups in their application easier. I’d claim though that for the majority of PHP users such setups are not a requirement. Why would those people need to follow PSR-0 just to use a piece of native PHP code then?

Coding conventions are not enforced by compilers. As a result, not following some or all of the rules has no impact on the executable programs created from the source code.

PHP works with any convention, not just one convention. PHP does not define a particular coding standard for userland code. There is a few tips and guidelines for how to name code in the global scope, but that is not a standard, nor a convention. It’s incomplete.

One could assume that since all examples in the PHP Manual follow PEAR convention, PEAR is the agreed upon convention in PHP, but that is simply not true. In fact, a lot of the projects that now participate in PSR did grow to reasonable size by inventing their own coding convention or tweaking an existing one. They didn’t need a general standard then, so why force one unto us now? By their success they have already proven that we don’t need such a thing in PHP.

The C implementation of the suggested ClassLoader is from PEAR’s own David Coallier. Yet, despite PEAR and autoloading being around for much longer than the PSR group, we do not have any code in PHP that requires us to follow PEAR convention. Ironically, if all of the projects taking part in PSR had followed PEAR convention for file and class naming right from the start they wouldnt have an interoperability problem now. But apparently, they didnt feel PEAR was good enough then. Who guarantees that they won’t abandon PSR in five years again? I’d rather have developers follow a convention by conviction than by embedding it into PHP.

To stress this, I am not against having a native classloader. But I am against putting it into SPL when it requires PSR-0. No other function in PHP requires us to use a certain code convention. The argument that it is optional doesn’t count. It is not a general purpose classloader when I have to follow PSR-0 for it and thus it shouldn’t be in SPL.

Also, what the PSR group should take into account is that frameworks evolve and change much faster and often than PHP. If they want their code to be in the PHP trunk, they have to follow PHP’s release cycles, which will make it a lot harder to introduce new features and BC breaks. Putting the classloader into a PECL extension would make much more sense then.

Incidentally, there already is a project in PECL that brings it’s own classloader. And in fact, YAF sounds a lot like where the PSR group is heading. The ClassLoader is just the tip of the iceberg. Once that one is in SPL, they want common interfaces to follow. Now why should PSR be in SPL, when YAF isn’t? Where do we draw the line?

In that sense, please keep PHP free from framework interests.
Don’t put the Classloader into SPL.
Thank you.

P.S. Some additional thoughts can be found in ircmaxell’s blog

Jun 20

How to install Zend Server from a local Repository

The following is a guide to do a manual install of Zend Server on RHEL 5/6. I needed this solution because I had to install Zend Server on a machine in an intranet with no WAN and the Zend Website only offered an RPM installer that required an internet connection.

Disclaimer: Note that the solution below worked for me. It doesn’t mean it will work for you. If you break something in the process, it’s not my fault. When in doubt, buy Zend Support.

Step 1 – Mirror the Zend Server Repository

When you are using the installer script, it will try to download the appropriate Zend Server sources from

so open a command prompt and mirror that location

wget --mirror --no-parent http://repos-source.zend.com/zend-server/rpm/

This will download all files at that location, including any optional extensions and some cruft. If you know your required cpu architecture, you can limit wget to mirror only the appropriate folders. Once you hit Enter, go make a coffee or something because this will take a while (about 315MB for Zend Server 5.1).

Upload the file to the target machine when done.

Step 2 – Download the RPM installer

You can get this one from the zend.com Download section. When done, upload and extract the archive on the target machine

tar xzf /downloads/ZendServer-RepositoryInstaller-linux.tar.gz

This will create the folder ZendServer-RepositoryInstaller in /downloads with all the contents of the archive. cd into that directory now.

Step 3 – Modify the repository file

You now have all the required files. Move the mirrored rpm folder to some convenient location, like /opt/zend-server/rpm or whatever you deem convenient. Then tell your RHEL about the new location.

Modify zend.rpm.repo to read the following:

[Zend] 
name=Zend Server 
baseurl=file:///opt/zend-server/rpm/$basearch 
enabled=1 
gpgcheck=0
gpgkey=http://repos.zend.com/zend.key

[Zend_noarch] 
name=Zend Server - noarch 
baseurl=file:///opt/zend-server/rpm/noarch 
enabled=1 
gpgcheck=0
gpgkey=http://repos.zend.com/zend.key

Step 4 – Install from the local repository

After you have made the changes to repo files, installing takes the same steps explained in the Installation Guide. If you are not on SELinux you can skip the following step

setenforce permissive

To install Zend Server, call the install script with the desired version, e.g. for 5.3 do

./install_zs.sh 5.3

Confirm any prompts with yes.

Zend Server should now be running at these URIs

And that’s it. You can do a yum clean all to clean up any meta data if you want and add PHP to your PATH environment to make it available on CLI now. Details for that can be found in the Installation Guide.

Alternative without the installer script

Instead of using the installer script, you can also add the zend.rpm.repo file to /etc/yum.repos.de/ and then do a yum install manually. This is the same as explained in the Installation Guide. The only difference is the local repository.

Additional Packages

Because you mirrored the full repository, you will also have all the optional packages now. You can install any of those with a regular yum install package-name. For the full list of additional packages, see

Troubleshooting

Error: Metadata file does not match checksum. Trying other mirror
Solution: yum clean all

Error: php-5.3-page_cache-… not found
Solution: check the given path and make sure the file does not contain url encoded values, e.g. %3a instead of :

Updating and Uninstalling Zend Server

Since your Zend Repo points to a local repository, you won’t get any updates. You have to replace updated content in the repository manually. Uninstalling works the same as with a non-local repository. See the Installation Guide for details.

May 22

Dutch PHP Conference 2011

From May 18th to May 21st I was at DPC in lovely Amsterdam. The line-up for this conference promised a lot of interesting talks and good networking opportunities. So I had to go.

Hotel

The speaker hotel for DPC11 was the ibis Hotel at Amsterdam Central Station. I considered staying there at first, but this was about 6km from the conference venue and (like any other hotel in downtown Amsterdam) it was quite expensive.

So I ended up in the CitizenM Hotel, which is a pretty fancy design hotel with rather small (no separate bathroom), but efficiently designed and quiet rooms. The bed was spacious and comfortable. Geeks will love the Philips mood pad that allows controlling various aspects of the room, like TV, blinds, air condition and lighting (including color). They also offer a huge list of free movies and WiFi is complimentary as well.

Venue

The RAI conference center was about 10 minutes walk through Beatrixpark from CitizenM. There is not much to say about the venue, which in this case means, it was well chosen. The WiFi worked well. The rooms were large enough to accomodate the PHP Crowd at the various talks. The main hall allowed for easy socializing. Some rooms were bit too cold at times.

Catering

I just might be a spoiled german here, but I was a bit disappointed by the catering. There was sandwiches, warm pastry and Hot Dogs for lunch, which I was told is pretty common for Dutch lunch. Unfortunately, the warm food was only available in very limited quantities. So, if you didnt get to the food stands immediately you were left with the sandwiches (which I wasn’t too fond of). The only good thing about this was you couldn’t fall into a post-meal coma and since I wasn’t there for the food anyways it’s just a minor complaint.

Workshop

Prior to the conference, there was a full day of workshops. Attendees got a free copy of thePHP.cc’s QA book, which was a rather nice and very much unexpected gift, especially since I didn’t own that yet and had it on my wishlist.

I attended “XP Principles and Practices” by Sebastian Schürmann. I already knew the theory behind XP, but the workshop helped me deepen and solidify my knowledge and helped close some gaps. The presenter did a good job moderating the workshop in a way that encouraged active participation of all attendees. There was a tremendous amount of experience shared this way.

Conference Day 1

The main conference started with Aral Balkan’s keynote about “The Art of User Experience: making beautiful, delightful, fun things”. While UX might not be a too obvious thing to think about when you are in the bowels of a PHP backend, Aral delivered an absolutely stunning and professional keynote that got the argument across in an entertaining, enthusiastic and inspiring manner.

After the keynote I attended Oracle’s Christopher Jones talk about Developing and Deploying High Performance PHP Applications. The talk had an (expected) sales-pitch nature, but I found it valuable to get an overview of current and upcoming Oracle Techologies I might want to look more deeply into. As such, the talk wasn’t so much about “How” but about “What with” and offered only very little technical details. And I got a free USB Stick, so yay!

Since I recently read “REST In Practise” and “RESTful Web Service”, I was keen to attend Evert Pot’s session “So you think you know REST?” then. Unfortunately, the talk focused way too much on various HTTP features and was very dry. I missed information about Resources, Representations, Richardson’s Maturity Model, the role of Hypermedia (HATEOAS) and how REST enables us to build Domain Application Protocols.

After the lunch break I attended Jonas Marien’s “Implementing Comet using PHP”. Whenever I researched Comet for PHP in the past, I came to the conclusion that PHP isn’t that well suited for it. I had hoped to gain some new insight on the topic, but the talk mainly offered a (very thorough) overview of available Comet technologies in general and not so much about the problems faced when wanting to do Comet in PHP. So the title was somewhat of a misnomer.

For the final session on that day I attended Rob Allen’s “Zend Framework 2.0: what’s new and what’s changed?”. This was a good talk that delivered what it promised. As I dont follow the ZF2 development too closely it was good to learn that a number of things that bug me in ZF1 are on the ToDo list for improvement in ZF2.

Socializing Event

The socializing event was scheduled from 2030 to 2300 in Club NL in downtown Amsterdam. Unfortunately, that venue didnt work for me at all. The place was way too small to accomodate all the attendees and it was definitely too noisy to socialize without yelling at each other. I left early.

Conference Day 2

The second day at DPC11 started with the Helgi Þormar Þorbjörnsson keynote about “First Class APIs”. Helgi emphasized the growing importance of making Data available on the web via dedicated APIs. While this was a solid keynote it paled in comparison to the furious keynote Aral Balkan delivered on the first day. I also felt it was rather lengthy with the main argument being sufficiently explained after about half of the keynote.

The first session I attended that day was Juozas “Joe” Kaziukėnas “The new era of PHP frameworks”. I didnt always get who Joe was refering to when he said “we” but the talk gave a good overview over the current state of PHP frameworks and what to expect from the next generation of PHP frameworks. Some of what was suggested as desirable features in next-gen frameworks was rather opinionated in my book and debatable (just add beer) but unfortunately, there wasnt enough time to do so.

When I left Rob Allen’s ZF2 outlook the day before, I had asked him about a specific problem I was currently facing in one of my ZF projects and he invited me to his talk “Optimising a Zend Framework application”. This was a very well done talk offering plenty of good practical advice (beyond what is already offered in the ZF Performance Guide) to take home.

After that I attended Qafoo’s “Modular Application Architecture”. Kore Nordmann and Tobias Schlitt presented different solutions to this problem and compared them. The talk covered a lot in a very short time, which made it sometimes hard to follow. For the short 45 minutes at DPC it might have made sense to just focus on an overview and leave out the obscure real world examples of Oxid and PHPBB. Still, a good talk.

The last talk for this day was David Zülke’s “Large-Scale Data Processing with Hadoop and PHP”. David is a very entertaining speaker with a skill to sell technologies to you in a very short time. Unfortunately, he had a headache this day and wasn’t as jumpy as usual. But even with this slight handicap, David delivered a professional and rock solid, well structured introduction to Hadoop and HadooPHP with some live demos.

The closing keynote of DPC11 was held by Cal Evans. Cal talked about what managers should know and do if they want developers to exhibit the same passion and enthusiasm towards their jobs than they show for open source projects they work on in their spare time. Though I am not sure I’d subscribe to all what was said, this was a solid and entertaining keynote with a clear message.

Conclusion

All in all, I really enjoyed DPC a lot. There was plenty of interesting topics to pick from. And despite the failed Social Event, I still had my share of socializing and networking between sessions. DPC11 was a rather valuable conference for me and I am looking forward to come back here next year.

Thanks to everyone who made this happen.

May 16

Iterating File Contents with Spl

I noticed a lot of people are still using the classic filepointer approach to read a file line by line:

$handle = fopen ("file.txt", "r");
while (!feof($handle)) {
    $buffer = fgets($handle);
    echo $buffer;
}
fclose ($handle);

While there is nothing wrong with doing things the old school way, PHP also offers SplFileObject for quite some time now:

$file = new SplFileObject("file.txt");
while (!$file->eof()) {
    echo $file->fgets();
}

Not only does this shorten your code by two lines, but it also let’s you work with an Object instead of a Resource now. Almost all of the procedural functions available for file handling are also available as methods of SplFileObject.

If that’s not enough reason to switch already, SplFileObject also implements the Iterator interface, which means you can shorten the above code to a simple foreach loop:

foreach (new SplFileObject("file.txt") as $lineNumber => $content) {
    printf("Line %d: %s", $lineNumber, $content);
}

There is more. Because SplFileObject also implements SeekableIterator you can easily jump to specific lines without having to count lines via some temp variable in your loop. How much more convenient can it get?

$file = new SplFileObject("file.txt");
$file->seek(9);        // zero-based, so it's line 10
echo $file->current(); // outputs line 10

And of course you can stack an SplFileObject into other Iterators, for instance the LimitIterator to limit how many lines should be iterated over:

$linesTenToTwentyIterator = new LimitIterator(
    new SplFileObject("file.txt"), 
    9, // start at line 10
    10 // iterate 10 lines
);
foreach ($linesTenToTwentyIterator as $line) {
    echo $line; // outputs line 10 to 20
}

SplFileObject is complemented by SplTempFileObject and SplFileInfo. The first offers an object oriented interface for a temporary file, including in-memory files. As such it is similar to file pointers opened with php://temp or php://memory as file descriptors.

SplFileInfo offers a high-level object oriented interface to information for an individual file. This includes methods for getting the realpath, basename and so on. SplFileInfo is actually the parent class of the other two.

So next time you’re going to whip out another file pointer, remember there is a nice OO alternative.

Reference

Apr 5

Announcing PHPUnit Schema

When working with PHPUnit's XML Config file, it can be somewhat tedious to remember all the possible configuration elements and how they should be written. For this purpose, I have assembled a PHPUnit Schema file to assist in authoring PHPUnit configuration files. And since I figured I am not the only one who could find that useful, I decided to share with you.

The PHPUnit-Schema is available on GitHub. Contributions and corrections are welcome. If you want to participate in maintaining and/or improving the file, feel free to fork at will. Pull requests are always welcome.

Usage

To apply the Schema to a configuration file, you have to declare the Schema Namespace and the location of the Schema file in the phpunit.xml file. Since PHPUnit does not use a dedicated namespace for the configuration file, the following two lines are all that is required:

<?xml version="1.0" encoding="UTF-8"?>
<phpunit 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="location of xsd file"
    

Assuming you are working with a Schema-aware editor (like Eclipse) you should get Content Assist and limited Code Completion then:

Contentassist

Notes

The Schema file is currently split into multiple smaller files. This eases maintaining the Schema file during development for me. But it's somewhat inconvenient, if you just want the Schema file for Content Assist. For this purpose, you can create a single phpunit.xsd with the PHP script given in the tools folder:

$ php generate-schema.php
Created new validated Schema file at:
 F:\Work\code\PHPUnit-Schema\tools\phpunit.xsd.1301999633
Mar 17

The DOM Goodie in PHP 5.3.6

PHP 5.3.6 has been released today. There is a lot of improvement and bugfixes that are worth mentioning. But the one that made me particularly excited was this one:

Implemented FR #39771 (Made DOMDocument::saveHTML accept an optional DOMNode like DOMDocument::saveXML). (Gustavo)

If you have worked with DOM before, you know that this will ease working with broken HTML a lot, because now you can do

$dom = new DOMDocument;$dom->loadHtml('<div id="content"><p>Some<br>HTML Fragment</p></div>');echo $dom->saveHTML($dom->getElementById('content'));

and get

<div id="content"><p>Some<br>HTML Fragment</p></div>

Why is it cool?

DOM is based on libxml. So it is primarily intended for working with XML. Broken XML cannot be parsed with DOM. And HTML isn't XML at all, but is based on SGML. Different rules. Unfortunately, even after years of advocating web standards, most of the web is still broken HTML. Pick a random site on the web and run it through validator.w3.org. My guess is at least eight out of ten sites will not validate (including this blog - not my fault though). And just to make this clear: I don't have any hopes that TMFKAH will improve the situation. A well formed web will forever be a Pipe Dream.

The good news is: despite common misbeliefs, DOM can also parse broken HTML. When you use loadHTML() or loadHTMLFile(), DOM will internally switch to it's HTML Parser Module and parse the markup as HTML4 Transitional.

The bad news is: when using the HTML Parser Module, libxml will also add a basic HTML skeleton to make sure it can parse the HTML somehow. This is a nasty unobvious side-effect, because when traversing the DOM with

$dom->documentElement->firstChild->nodeName;

you would expect it to output 'p', but it will output 'body'. Consequently, when we used saveHTML(), we would get the following output (shortened DocType for readability):

<!DOCTYPE html PUBLIC "blah"><html><body><div id="content"><p>Some<br>HTML Fragment</p></div></body></html>

To make matters worse: with saveXML() you can pass in a node to be dumped. With saveHtml() you couldn't (until now). So when you were dealing with HTML fragments, you had no way to get just a particular node or fragment back from DOM. You could get all or nothing. The only two options you had was manually removing the HTML skeleton somehow or dump the wanted nodes with saveXml instead. Using saveXml had the problem that it would format any markup according to XML rules as well, so <br> would become <br/>. If you didn't intend your markup to be XHTML, this is unwanted.

But with PHP 5.3.6 we can finally pass a node to saveHtml. And that's very cool!

Tweet a "Thank you" to Gustavo for implementing it.

Note: For some reason I cannot get Posterous to format the code properly. Sorry for that.

Feb 26

PHP Unconference and PHPDays in Manchester

I had the pleasure to attend the first PHP Unconference Europe and the PHP Days in Manchester. I knew there would be a couple of people I wanted to meet in person. Also, I’ve never been to Manchester before. So I decided I had to go. Happy I did, because I had a great time.

Warm-Up

Before the actual conference, about 25 people met in a pub for the warm-up party. I was introduced to what the British consider beer (I’d rather call it Mock Beer or Beer Doubles) and quickly got into smalltalk with the other conference attendees. Since the Conf would start at 9am the next day, I left at about 11pm to get some sleep.

Day 1

The PHP Unconference in Manchester is the first spin-off of Hamburg’s PHP Unconference. So it was no suprise that a good quarter to half of the 100 attendees were german. Judith Andresen kicked off the conference with a short speech before she explained how the Session voting works: you got four votes per day, which you can use to vote for any available Sessions. The Sessions with the most votes wins. There is two Sessions in parallel.

The first talk I attended was Lorna “lornajane” Mitchell’s “Speaking Tips for Developers”, which I liked very much. Lorna gave a highly enthusiastic talk with lots of useful advice for anyone who ever wants (or has) to speak in front of an audience.

I heard “Dealing with Errors” by James (last name?) then. I didnt agree on all the suggestions on how Error Handling should be used in PHP, but all in all, the Session was a good round-up of the various error handling mechanisms.

After that I saw Volker Dusch’s talk “Clean Code – Stop wasting my time”. The talk mainly focused on superfluous commenting in source code, doc blocks and commit messages. Again, quite interesting and also quite entertaining due to Volker’s ranting presentation style.

It’s not so much about the talks than about the coffee breaks – Judith Andresen

Along the lines of that quote I skipped the next session to meet Mark Baker of PHPExcel then. I only knew Mark from StackOverflow so far and was happy to finally meet him in person. Was a pleasure.

The last session of the day was Arne Blankert’s talk “PHPDox – an alternative to PHPDocumentor”. PHPDox aims to finally supersede the aged PHPDocumentor tool. At the time of the conference, phpdox was nearing completion and looked quite promising already. It’s available on github.

After that it was socializing again. The conference venue, Pitcher and Piano, is a bar chain so we didnt have to relocate for the evening. The second floor was reserved for us. I spent quality time with good talking and a couple of free drinks sponsored by the conf organisers before heading back to the hotel at about 11pm again.

Day 2

When we arrived on the second day, they were still cleaning the room. So there was some delay before the voting and the sessions could start.

I attended “Building a successful development team” held by Stefan Priebsch and Judith Andresen. This talk was an open discussion about the topic. Although there was some good points mentioned what makes a good team and what is hampering it, I felt the discussion was too superficial. But interesting nonetheless.

After that I saw the completely PHP-unrelated talk “HTML5 and Friends” by Patrick Lauke, Web Evangelist at Opera. This was a very thorough, professional and lengthy talk and Patrick had to continue it long into the lunch break to finish it. It couldn’t lessen my bias towards HTML5 though, as I don’t believe in “bling”.

HTML5 is HTML4 with added bling – Patrick H. Lauke

Then I heard “Automated Release Procedures for the Web / DB Versioning and Deployment”. This was an open discussion again and I didn’t get too much out of it for myself. I like to leave a Session with at least one “I have to try that at home” thought.

The final session was “Setting up Jenkins CI for PHP Projects” held by Sebastian Bergmann and Volker Dusch (again). They introduced their PHP Template for Jenkins and ran through setting up the Continuous Integration Server for usage with PHP QA Tools, like phpunit, pdepend, phpmd and so on. Very useful talk.

After that the organisers held a short closing speech and were (rightfully) applauded by the remaining attendees.

Venue

Originally, another venue was considered. But because there wasn’t enough tickets sold when the venue was finalised, the choice was made for the Pitcher and Piano. So, next year, buy your tickets early and give the organizers some more financial room for planning.

Like already mentioned, Pitcher and Piano is a bar chain. Doing a conference in a bar works, as long as there is no other visitors. Unfortunately, the bar would allow other visitors into the bar though. Naturally, there noise level rose the later the day. This was somewhat annoying when attending talks upstairs, because music and talking from the main bar would disturb the speakers. Apart from that, the venue worked suprisingly well for me.

Catering

Let’s admit it: the PHPUnconference in Hamburg spoiled me. You get breakfast, lunch, cake (not a lie) and unlimited coffee, tea and softdrinks for free. All very tasty and easily on par with the catering at a commerical conference, like IPC. If there was no talks at all, I’d still attend for the food alone.

I had expected a similar pampering in Manchester. I didn’t book breakfast at my hotel and I didn’t bring any drinks. Both mistakes, because there wasn’t any breakfast and no drinks during the day, except for coffee, tea and lemonade. All of these were made from tap water, which I wasn’t the only one who felt tasted odd, quoting:

Wondering if they use canal water for the tea and coffee #phpuceu – antz29

Because of that I bought all my drinks at the bar instead (until we got our vouchers for the party).

The lunch on both days was solid. So was the dinner on the first day. I remember there was lasagna, chili, curry and assorted salads and side dishes. Vegetarians had their options, too. Some attendees told me they felt the food tasted rather bland. I felt it was okay (and there was salt and pepper available anyways). So, nothing to complain about here.

PHP Days

As part of their sponsoring, thePHPcc aka Sebastian Bergmann, Stefan Priesch and Arne Blankerts offered a two day training after the two days conference. All training fees would go directly to the Unconf, so they actually held the training for free. Because I had already attended both PHPSummit’s held by thePHPcc last year and found them very valuable, I was eager to participate in this training.

The PHP Days were held at the Manchester Conference Center with just eight attendees (five of them german). All of us already knew a fair share about PHP, so discussions were at an enjoyable intermediate to expert level. It’s also quite fun to see thePHPcc lecture together, as one of them will usually always play Devil’s Advocate. Plus, there will a good portion of geek humor involved.

Since we could decide where we wanted this training to be headed, we decided to build a joind.in clone (we didn’t finish it though). So we discussed the problem domain while thePHPcc would write the code and the UnitTests for us. As the code evolved and domain knowledge got better, we would apply needed refactorings.

Inbetween there was lunch, tea, coffee and cookies.

On the second day, thePHPcc showed us how to create a minimal MVC framework around our new Domain classes. We also talked about how to use the Dependency Injection Principle to avoid tight coupling in our classes. And we talked about how to properly divide functionality into framework, application and domain classes to get the responsibilities right. This was very insightful, even for seasoned developers. The last two hours of the training, we talked about how to deploy our application.

Conclusion

Despite a few shortcomings, I really enjoyed PHP Unconference Manchester. It was a great event with great people and good talks. I am looking forward to attend next year.

The PHP Days training was fantastic and I can happily recommend it to any seasoned developer. Looking forward to attend this next year again as well (if it’s offered).

In short: thanks to everyone who made these four days possible and awesome.

Jan 20

Becoming a Zend Certified Engineer 5.3

I took and passed the Zend Certified Engineer PHP 5.3 exam recently at my local Pearson Vue Test Center. I bought the certification bundle in early 2010 already. But due to a limited time budget, taking the exam had to wait until early January 2011. Now I can pride myself with … well, with having passed it. Or as the certificate puts it

Has successfully completed the test requirements and demonstrated the knowledge and skills to be recognized as a Zend Certified Engineer PHP 5.3

001

What does it mean to be a ZCE?

I think the text on the certificate is appropriate. In my opinion, passing the test requirements says very little about being able to successfully pass the real-world requirements on your next project. It wouldn't be fair to expect that from a test like this anyway. Though the testimonials on Zend.com suggest different, I also wouldn't expect the certificate to help too much with job offers either. If anything, it might give you a headstart. But it's likely not enough to make you win the race. Or as someone on StackOverflow put it:

The Value of an Zend Certified PHP Developer, for me personally, only lies in the fact that we can skip the "is he/she a complete moron that knows nothing about programming at all".

While that quote is a bit drastic, the author gives some valid points about professional PHP development later on. PHP has evolved a lot in recent years. So have the available frameworks, tools and methodologies. These are out of scope for the exam though. The exam only tests your working knowledge of PHP and it's API. Passing it ensures you have a good and necessary foundation. Nothing more, nothing less.

Tell me more about the exam

Because I had to cross my heart and swear to die not to tell anyone about the actual questions in the exam, I cannot write too detailed about it. I guess it's okay to give a few hints as to what to expect from it though, since that is openly available in the official FAQs anyway.

The exam is a collection of 70 questions, covering a good range of PHP and web-related topics. The questions are either multiple choice or free input. Question tasks include analyzing code snippets for what they are doing. Or they might ask for appropriate functions, methods or interfaces applicable in a given scenario. There is also the occasional question about Design Patterns (at least in the Mock Exams).

Unfortunately, there is also a good portion of what I like to call "memo-questions". These will ask you about argument order or which variation of a function name exists. Personally, I find those type of questions completely pointless. If I forgot whether the $haystack or the $needle comes first, I know where to look. Same for function names. Those questions should definitely be ditched.

You do not get penalized for wrong answers. If you don't know an answer, guess. To my knowledge, the questions are picked randomly, so no test is alike. There is some logic that makes sure you get a certain amount of questions from certain areas. Somehow they have to make sure this is a PHP 5.3 exam, right?

You got 90 minutes for the exam, which is plenty. I finished 15 minutes earlier. You can mark questions during the exam, which makes reviewing your answers in the end quite easy. Once you are satisfied with your answers, you submit them. You'll get the result immediately. If you pass, you'll get listed with the Zend Yellow Pages in a day or two. A few days later, you'll receive your official certificate from Zend.

How did you prepare for the exam?

I bought the ZCE certification bundle. It contained the official Study Guide, ten Mock Exams and the voucher for the exam. The Study Guide and the Mock exams are for the ZCE PHP5 exam. Given that I had less than a dozen or so questions about PHP5.3 in the real exam, I consider both to be still well suited for preparation. I mostly ignored the Study Guide and only glanced through it to get an idea of what areas I should be knowledgable of.

Like their name suggests, the Mock Exams simulate the actual exam. I felt those are quite helpful to find out what to expect. I did two of the Mock Exams and passed them both with an "Excellent" grade immediately. You get a detailed report in the end, telling you how you fared in certain areas. Obviously you should improve your knowledge in those areas you scored low.

However, the best preparation is to actually read and write working code. 

So the exam was easy?

No. Actually I was suprised when I took the exam. Maybe I was just unlucky but there was a number of questions where I was unsure or had no clue. Unlike in the Mock Exams you do not get a detailed report for the real exam, so I don't know how I fared compared to the Mock Exams. But they definitely felt easier. I wouldn't suggest to take the exam lightly or without passing the Mock Exams with high grades.

What others had to say

Find out how other developers think about the Zend Certified Engineer 5.3 exam and how they prepared for it:

Jan 17

Why Singletons have no use in PHP

I am pretty sure everyone working professionally or semi-professionally has heard, seen or worked with a Singleton before in one way or the other. For those of you who never heard of it, let me reiterate the purpose of that Design Pattern:

  • Make sure there can be only one instance of a class at any time.
  • Provide global access to that single instance from anywhere within your application.

You'll often find Singletons as wrappers around database adapters to limit the amount of connections. Another popular use is to make Front Controllers or a Registry into Singletons.

Implementing Singletons

Unlike some other patterns, creating a Singleton is easy.

Singleton

  • Add a static getInstance() method to allow global access.
    • Call the Singleton's constructor on first call
    • Assign the newly created instance to the $instance property.
    • Return $instance on subsequent calls.
  • Make __construct() private to prevent direct instantiation from outside.
  • Make __clone()private to prevent cloning from outside.
  • Make __wakeup() private to prevent deserializing from outside.

There is a similar sample implementation in the PHP Manual as well. Variations of that implementation exist in other languages. In PHP this one is the dominant variant though, mainly due to language constraints.

However, despite it's apparent usefulness and wide adoption, the Singleton is also controversial. Many developers see it as an AntiPattern nowadays and I tend to agree with them.

Singletons are not unique snowflakes

In languages where objects live in an application server, Singletons can be used to keep memory usage low. Instead of creating two objects, you reference an existing instance from the globally shared application memory. In PHP there is no such application memory. A Singleton created in one Request lives for exactly that request. A Singleton created in another Request done at the same time will still be a completely different instance. And it will occupy it's own memory. Those instances are not linked to each other. They are completely isolated, because PHP is a Shared-Nothing architecture. You do not have one single unique instance, but many similar instances in parallel processes. Thus, one of the two main purposes of a Singleton is not applicable.

Don't construct twice, it's all right

Advocates of the Singleton in PHP often argue it's still useful to be able to limit an instance within a single request. The aforementioned database classes being the most prominent example. But the much easier solution would be simply not to instantiate a second instance. If anyone can make sure there is just one instance, it's the developer. If you need to have the same instance in many classes, use Dependency Injection. Just create one, inject everywhere. That will also save you the hassle of deconstructing your Singleton once you notice you need a second instance of it all of a sudden.

Another example where Singletons are often applied but don't make sense is classes like FrontControllers. While conceptually it makes sense to say "There may be only one FrontController", it is superfluous to ensure it from an architectural viewpoint. A FrontController is usually instantiated only once in your application's control flow anyway. If you don't write a new Foo; anywhere else, you already made sure there is just one instance. So you ain't gonna need the Singleton here. Don't express concepts in your code that are never used.

Don't shoot yourself in the foot

The Singleton's other purpose (to have a global access point to the instance) is undesirable in PHP. The desire for that usually stems from having an architecture where objects pull in their dependencies. Like any globals and statics, the Singleton's getInstance() method creates coupling to the global scope. This makes Unit-Testing harder. There is ways to mitigate this, but in general, the cost to mitigate is higher than to simply avoid the Singleton in favor of Dependency Injection. This is especially true in those situations, where the Singleton is applied but never instantiated twice anyway.

Closing Notes

When working with PHP, Singletons cannot live up to their full potential due to PHP's Shared Nothing architecture. They are also introducing a number of undesirable disadvantages that will make your application less maintainable and harder to change. And to add another sure sign that you should be wary of the Singleton: even Erich Gamma, one of the pattern's inventors,doubts the Singleton nowadays:

I'm in favor of dropping Singleton. Its use is almost always a design smell

Hopefully this is enough to make you reconsider next time you think about using a Singleton. Should you still have trouble deciding, use the following cheatsheet:

Singleton

Links

About gooh

I'm a webdeveloper from Essen, Germany with a focus on PHP, Zend Framework and frontend technologies.

Search Blog

Get Updates

Tags

Archive

2012 (2)
2011 (24)