Zend Framework 1.8 Web Application Development review

Packt Publishing sent me a copy of Keith Pope’s Zend Framework 1.8 Web Application Development a while ago. In return they asked me to write what I thought about it. I have had it lying on my desk for a while but haven’t had time to read it more carefully. Nevertheless I have actually used it every now and then. Now, after reading a bit more the last few days, I can finally give my opinion on the book.

Programming books in general

I’d better start off with telling you that I haven’t read many “pure” programming books since the mid 1990’s when I was studying at the university. I tend to stick to books on concepts and methodologies and then read online tutorials and articles when it comes to programming. Programming books are rarely worth the money as they are either reference books which gets out of date quickly (I’ve thrown away quite a few Java books over the years…) or learning by example books which you painstakingly slowly must follow line by line to build something thousands open source projects alrady built.

My thought was that this book was probably both outdated (as ZF 1.9 has been around for awhile) and probably boring in that building a web shop isn’t that interesting. I was wrong in all ends.

The book

I especially like the way Pope introduce the MVC concept in Zend Framework. In the first chapter you get a good overview on configuration, the bootstrap process, controllers, action helpers, views and error handling. Chapter two goes deeper into the specifics of the request and routing. He also briefly delves into more advanced topics as plugins and component customization. The reader quickly gets a very good grasp on how to work with MVC applications in Zend Framework.

Another thing I like is how Pope reasons about various strategies; both pros and cons as well as how and how not to do things. Good examples are chapter four where Pope gives a good explanation on the Fat Model Skinny Controller strategy and chapter five with it’s best practices regarding accessing models from views with the help of view helpers. Reasoning and explanations like this is good, especially for unexperienced developers. This – and giving optimization and testing their own chapters – makes the book better. As Pope is thowing in both Zend Tool as well as Ant into the book makes it even better still.

Summary

To sum up my opinions the structure of the book makes it easy to read at leisure as well as using it as reference later. The MVC concept and how it is used in ZF is way better explained than in the ZF documentation. (Truth be told the documentation is hopeless here.) I’ve been working with ZF a “long” time now and whether the book is better for complete beginners or programmers at least a little bit familiar with Zend Framework I really can’t tell. Remembering how I struggled to find a good introduction to various topics found in the book I belive this book is a better introduction to Zend Framework than can be found in online tutorials and articles – or even the online documentation.

However, a beginner will get more out of this book than just learning Zend Framework. He, or she, will also learn about unit tests, build procedures and best practices.

PHP

Free weather icons

The Norwegian weather service Yr.no is very popular in the Nordic region as they release weather data for free. We (as in the Swedish web development company Dotvoid AB) have used their service to create mashups and services as many others have before us.

Recently Malin Holm converted all our old bitmapped weather icons to SVG and we decided to release two png versions (60×50 and 120×100) licensed under the Creative Commons Attribution No Derivative 3.0 Unported License. All icons are named after the weather codes used by Yr.no but can of course be used for other data.

Download the full weather icon set at the Dotvoid AB icon page.

Weather icons
Weather icons
Web

10 years of English blogging

Even though I’ve lost my earliest blog posts due to an early domain change as well as a later change of blogging software I have been blogging about PHP and web development here for almost 10 years. As it is just over one year since we started our Swedish company Dotvoid AB I felt it was time to start blogging in Swedish as well.

I will continue to blog about PHP, javascript and web development here. I might even try to increase the number of posts. Oh I’ve never promised myself that before, have I ;) Anyway, our Swedish blog will not be as technical as here on dotvoid.com. Instead the blog will focus on the company and what we do as well as web development in Sweden and Europe in general.

PHP, Personal

PHP, SOAP and operation signatures

After investigating SOAP further there seems to be a common confusion regarding the difference between rpc/literal and document/literal and how it is handled in PHP. There is even a bug 49169 reported because PHP ext/soap maps all operations defined in the web service with the same signature to the first defined function or method in PHP when using document/literal style.

It is not a bug. The style document/literal is for sending messages with document data. It is not a remote procedure call. For that we have rpc/literal. So if you look at it that way it is completely understandable that only one method should be around to handle one specific type of message (document).

It is also completely correct behaviour according to the specification WS-I Basic Profile.

“In the case of rpc-literal binding, the operation name is used as a wrapper for the part accessors. In the document-literal case, since a wrapper with the operation name is not present, the message signatures must be correctly designed so that they meet this requirement.

As document/literal is the preferred style, and some implementations obviously have a tendency to dislike rpc/literal, a lot of people is going down the document/literal route without understanding the implications and what the real difference really is.

I don’t think this should stop ext/soap in PHP to use the soapAction header for routing when necessary. According to WSDL 1.1 the soapAction attribute is mandatory when HTTP protocol binding is used. Whether rpc/literal or dcoument/literal style is used is of no difference. So is this information just garbage for document style messages?

Anyways, PHP bug 46169 is to my understanding not really a bug. But it is a reasonable feature request.

PHP

PHP and Web Services – essential reading

An old web service implemented in PHP have been giving me some headache the last couple of days. Especially interoperability with clients implemented in other languages (like .NET) are troublesome. It seems to me that PHP is very forgiving. Which is good – sometimes – but not always. PHP let you get away with a lot when creating your web services. So just because your PHP client play along nicely doesn’t mean other clients will work. Far from it.

So after loads of googling I came to realise that even though 2010 is just around the corner there are still very few quality articles on PHP and web services/SOAP available. Most of the stuff I find is rubbish where people who don’t know nothing explain things they don’t understand.

So even though these articles below are old, they will give most people a very good grasp on how, and why, to create a SOAP web service using PHP that will work. (And a very short advice; use document/literal style for better interoperability with for example .NET and don’t use preserved words like “ref” as parameter (message parts) names for better interoperability with for example .NET).

  1. Which style of WSDL should I use?
  2. PHP SOAP Extension

A comment about the second article is in place though. I generally tend to favour mapping WSDL defined operations to methods in a class. So instead of using PHP methods like $server->addFunction(), use $server->setClass(). More on setClass() in the manual.

PHP

Inspiration time

I stopped working as an employee to work both on my own projects and as a freelancing consultant almost two years ago. This last year has been more like a roller coaster than anything else before. From spending very little time on my own projects while working as an independent contractor on debt collection systems with lots of integration to working on large scale public websites in a fast paced startup and then slowing down to work mostly on my own small projects again. During this time I have moved with my family from Karlskrona in Sweden to the south of Spain and then back to Sweden. This time we moved to Kalmar.

Even though free time has been somewhat scarce I have tried improving my routines when it comes to development and coding. But as the workload has been going up and down a lot I’ve mostly used the few slow periods to relax. I haven’t been to a PHP conference since 2007 and a more general software development conference since 2006. I feel I’ve been, work aside, somewhat lazy the last two years.

So I decided it is time to read a bit more on agile methologies, Zend Framework, setup a completely new laptop development environment using Ubuntu 9.10, Zend Studio 7.1 and Zend Server. I will also try out Mingle from Thoughtworks for project management. Ok the last thing can be a bit weird having only one additional team member besides myself on current projects. But I’ve been interested in trying it out ever since hearing about it by Dan North from Thoughtworks in an software development conference a couple of years back. Expensive but interesting to see if it can be used in teams trying to stay agile even though they are spread out geographically.

At the moment I’m rereading the excellent book Practices of an Agile Developer. It is a brilliant book packed with inspiration that can help you develop and improve your habits for an agile approach to software development. It is good to browse through it every once in a while to remind yourself on how you should work ;) Conveniently enough I was also just recently shipped a copy of Zend Framework 1.8 Web Application Development which I hope will be an interesting read as well. I also feel it is about time I read a more in depth book on XP or Scrum. I’ll see what good books I can find on that topic.

So the next few weeks, when I’m not working or trying to be a good dad to my daughters, I will try not to shut down my brain in front of the TV and instead study for a bit.

In my experience, trying out new things and reading a few good books, can do wonders to your inspiration and also give you more energy to face both challenging as well as more mundane, even boring, tasks.

PHP, Personal

Site architecture based on Zend Framework

After working on the Swedish weather site klart.se for awhile I now work on my own projects again. So I have switched Codeigniter to Zend Framework again.

After a trip to Dublin I finally launched the beginning of a new social tourist Dublin guide. It is exactly the same site as both the Swedish Fuengirola guide as well as the English Fuengirola guide I launched after living there for five months. The functionality is somewhat basic as of yet but every now and then I’ll add something more.

Basing three different sites, even though they are very similar, using two different languages gives me the possibility to try out several parts of Zend Framework. It also requires a good design both in the backend and frontend to keep it maintainable. I thought maybe some people would be interested in a basic overview of the different parts needed to put everything together.

Backend

The sites aren’t really that complicated. On a basic level there is a MySQL database and a database layer using Zend_Db/Zend_Db_Table, there is a Zend Framework MVC architecture using models, controllers, views, layouts with Zend_Layout as well as a few view helpers and some HTML, CSS as well as Javascript. All commonly needed. There is more needed to make it a sitethough.

I want as little configuration per site as possible but I naturally still use Zend_Config_Ini for settings. Zend_Registry is needed to keep the global scope clean and is used to store instantiated objects that need to be available throughtout the website logic.

I have been a bit particular on using ZF as often as possible on these sites. With few exceptions. Thus I also use Zend_Form, Zend_Locale, Zend_Translate, Zend_Cache and more. Zend_Cache is really a no brainer and mainly used to speed up translations. This is extremely easy as Zend_Translate and Zend_Locale both are connected to the cache with one simple method call each. It is not complete but how simple this is to setup is illustrated by the below code.

$configuration = new Zend_Config_Ini(
    APPLICATION_PATH .'/config/app.ini',
    APPLICATION_ENVIRONMENT
);
$frontendOptions = array(
    'lifetime' => $config->cache->lifetime,
    'automatic_serialization' => true
);
$backendOptions = array('cache_dir' => $config->cache->dir);
$cache = Zend_Cache::factory(
    'Core',
    'File',
    $frontendOptions,
    $backendOptions
);

$conf_locale = $configuration->locale;
$locale = new Zend_Locale($conf_locale);
$locale->setCache($cache);

Zend_Translate::setCache($cache);
$translate = new Zend_Translate(
    'array',
    APPLICATION_PATH .'/config/translation-' . $conf_locale . '.php',
    $conf_locale
);
$translate->setLocale($conf_locale);

Zend_Form have had a few problems in many versions of ZF. In my opinion it is also a bit bloated and limiting to be used all the way. (Even though I like the automatic connection to the translation functionality in Zend_Translate and the validation through Zend_Validate) So I have settled for a simpler way where I use Zend_Form fully for validation (with Zend_Validate) and then give the view access to the form through a Zend_Form subclass to be able to print the fields individually. I think this is easier to handle than all the overloading and coding needed to fully make Zend_Form create forms as I want them. Another good thing with the form classes is that they too are locale aware and are translated automatically by connecting them to Zend_Translate through the simple line Zend_Form::setDefaultTranslator($translate);. The sub classed Form utility class looks like below. The generated elements are translated automatically. Very convenient.

class Custom_Form extends Zend_Form  {
    /**
     * Render a field
     * @param string $name The name of the form element
     */
    public function _e($name) {
        $e = $this->getElement($name);
        return ($e) ? $e->render() : "<dt>Error</dt><dd>Missing <$name> field element</dd>";
    }
}

Another thing needed for these sites are to keep the urls understandable and thus translated into the language used on the site. For this the routes, or paths, are kept in the translation file as well. The translated paths are then registered to the router through the use of Zend_Controller_Router_Route and Zend_Controller_Router_Route_Regex objects.

$frontController = Zend_Controller_Front::getInstance();
$router = $frontController->getRouter();
$router->addRoute(
    'route_review',
    new Zend_Controller_Router_Route(
        $translate->translate('route_review'),
        array('controller' => 'review', 'action' => 'index')
    )
);

For image manipulation I haven’t looked further than ImageMagick. After a bit of tweaking you get very good quality when producing different image sizes.

Search

Last but not least, on the backend that is, there’s the search engine. ZF have an implementation of Lucene through Zend_Search_Lucene (derived from the Apache Lucene project). This is the one time I haven’t gone with ZF as I very much like the open source Sphinx search engine as it is so easy to integrate with MySQL. So Sphinx get to power the search.

This is convenient for several reasons. MySQL is not a great full text search engine, Sphinx give you better weighted results. The main reason though is the performance. Sphinx is very fast in itself but for a site with heavier traffic it is as simple as moving the search backend to it’s own machine to get a performance increase.

Frontend

On the frontend there is as clean html as possible to make it easy to change the design with only CSS as well as manipulate the client side with JQuery. If it wouldn’t be for the Google map the site would actually be pretty useful even without no css style at all.

A good practice I learned just recently (remember I’m mostly a backend developer) is to base all javascript functionality on modules that are instantiated depending on element ids present in the html. This makes it a lot simpler to split the javascript functionality into manageble pieces and also makes it a lot easier to maintain.

There are functionality in the client side javascript used to display error messages and information. This makes it necessary to create one javascript file with translation stirngs for each language. The correct javascript translation file is chosen in the layout (template/view file) depending on the current locale.

The map used is (are there any alternatives) Google Maps API. I chose to completely initiate the map by scanning the actual data displayed on the page. This is possible through clean html markup and also means that if I choose to list ten reviews on a page instead of five nothing need to be changed at all in the frontend. Only a loop limit on the backend.

Conclusion

Well. No conclusion. This was just a very basic walkthrough of most of the different pieces needed to create a fairly simple Zend Framework based website. Mostly it was a walkthrough of the bootstrap… I still hope it is useful or at least interesting.

I know I find it interesting to read about other sites and the architecture and design behind them.

PHP

Problem with downloading files with Internet Explorer over HTTPS

This behaviour has bitten me before. Yesterday I was asked to resolve the issue again. And as my memory is short I was again forced to search the web for a solution. The solution is simple – but also stupid.

The problem is that Internet Explorer does not handle file dowloads without caching over https very well. Or at all. According to knowledge articles on Microsofts website the problem occurs when having one or two of the http headers:

Pragma: no-cache
Cache-control: no-cache,max-age=0,must-revalidate

Previously I have have just omitted the http header “Pragma: nocache” for IE but it seems it does not always help.

So, whether you want it or not, the solution to the IE https download cache problem is to tell IE to cache the file.

if ((isset($_SERVER["HTTPS"]) && strtolower($_SERVER["HTTPS"] == "on")) &&
    preg_match("/MSIE/", $_SERVER["HTTP_USER_AGENT"])) {
	header('Pragma: cache');
} else {
	header('Pragma: no-cache');
}
PHP

Weather, photo sharing and PHP

I have been working on some really fun PHP projects with some really cool people the last six months. This has kept me busy both day and night so, naturally, blogging have not been a major priority. After creating a new Spanish photo sharing site fotos.es which took a few months we started on a Swedish project. And now, we are finally launching the best Swedish weather site, klart.se. As weather is what Swedish people talk about whenever they meet, a quality Swedish weather site is needed ;)

Even though all the project members are located in many different locations in both Sweden and Spain most things have gone really well.

After having been in Spain for the last six months it looks like it’s time to move on. In a few weeks we’re probably moving to Kalmar, Sweden. We haven’t lived in those parts since we moved to Dublin in 2000 and even though I really enjoyed my time here in Spain I am a looking forward to moving back home.

PHP, Personal

Zend Framework – file input labels are not translated

I hade some time over and updated one of my own projects to Zend Framework 1.8.1. Apart from a change in the auto loader API everything went smooth. But I was a bit annoyed to find out that a simple translation bug still was unfixed. As my project is going live soon I need that bit fixed.

The bug is known and open so I didn’t need to report it. I voted for the issue to be fixed, waited two minutes and still no fix… I thought that was how open source projects worked ;)

Seriously though, I fixed the issue locally and added what I think should be a correct fix in the comments. (Even though I think it is weird that the transfer adapter should even have the remotest connection to translation logic.)

http://framework.zend.com/issues/browse/ZF-6647

Looking at the statistics for Zend Framework issues I think it is time to step back and slow down on implementing new features. The diff between new issues and resolved issues is constantly getting bigger and bigger while the average time to fix an issue is getting longer and longer. This is natural as the project constantly have grown since it’s birth. But as I like working with ZF I’d hate to see it become a big and unruly behemoth that adds more problems than solutions.

PHP