The Developer Day | Staying Curious

CAT | PHP

Feb/10

18

Domain Model Logic Patterns

A great thing about patterns is that it provides a vocabulary. It allows developers to communicate efficiently. Complex ideas can be described at a high technical level without going into small details. Patterns are like butterflies and come in many colors, sizes and shapes and there’s.. lots of them. As butterflies patterns are grouped into families. One of such families is Domain Logic Patterns described in Martin Fowler’s book Patterns of Enterprise Application Architecture.

It’s one of the fundamental families because virtually every application written is described by any of the three patterns that belong to it. To say it simply there are three major ways how an application can be designed. What is more interesting that each of those patterns can be sorted by the amount of effort required to change the application depending on it’s complexity. Deciding which pattern to choose can be tricky because these patterns depend on various characteristics of the project being developed. The size, the complexity, the lifetime of a project and most importantly the skills of the developers.

Transaction Script

Transaction script organizes business logic by routines where each routine handles a single request from the presentation layer. It is the most common way how software beginners write applications. Required steps to perform a task are identified and expressed using language semantics. Common routines can be broken into subroutines. Transaction Scripts can be organised as classes or as global functions. A single file can contain many Transaction Scripts at once. A lot of developers may think they are proficient OOP users while in reality they write data centric Transactions Scripts wrapping them into classes which could be just as easily replaced with simple procedures.

However Transaction scripts have benefits. It’s a simple procedural model so most developers can understand it, it works well with a simple data access layer using Row Data Gateway or Table Data Gateway.

An example transaction script may be booking a hotel room where a single procedure is responsible for checking the availability of the room, calculating the price and updating the database.

class Hotel
{  
	public function __construct(Data_Access_Gateway $gateway)  
	{  
		$this->_gateway = $gateway;  
	}  
	public function bookRoom($userId, $fromDate, $toDate)  
	{  
		$roomId = $this->_gateway->_getRoomIdBetweenDates($dateFrom, $dateTo);  
		if (!$roomId) {  
			return false;  
		}  
		$days = $this->_getAmountOfDays($fromDate, $toDate);  
		if ($days < = 7) {
			$price = $days * 100;
		} else { 
			$price = $days * 80;
		}
		$data = array(
			'userId' => $userId,  
			'roomId' => $roomId,
			'fromDate' => $fromDate,  
			'toDate' => $toDate,  
			'price' => $price,  
		);  
		$bookingId = $this->_gateway->insert('bookings', $data);  
		return $bookingId;  
	}  
}

Table Module

A Table Module is many ways the middle man between a Transaction Script and a Domain Model. A Table Module tends to organize domain logic with one class per table in the database. While a Transaction Script will have one class Hotel to do reservations a Table Module may have more fine grained classes like Hotel, Booking, Room. Even though these classes may be singular they do not actually represent individual entities and manages whole collections of entities. For example a Booking class would be responsible for mosts actions performed on the bookings database table. Like a Transaction Script a Table Module is a very data centric model approach and usually has a strong connection with the data access layer.

Table Module has a few benefits over a Transaction Script. There’s less duplication, domain logic is more organized and structured around domain entities. It works well with simple data access layers. However, Table Module doesn’t give you full power of objects in organizing complex domain logic. It lacks instance to instance relationships, has weak support for polymorphism.

To show an example of Table Module let’s re-factor the Transaction Script:

class Hotel
{  
	public function __construct(Data_Access_Gateway $gateway, Booking $booking)  
	{  
		$this->_gateway = $gateway;
		$this->_booking = $booking;
	}  
	public function bookRoom($userId, $fromDate, $toDate)  
	{  
		$roomId = $this->_booking->getRoomBetweenDates($fromDate, $toDate);
		if (!$roomId) {  
			return false;  
		}  
		$days = $this->_getAmountOfDays($fromDate, $toDate);  
		if ($days < = 7) {
			$price = $days * 100;
		} else { 
			$price = $days * 80;
		}
		$bookingId = $this->_booking->addBooking($userId, $roomId, $fromDate, $toDate, $price);  
		return $bookingId;  
	}  
}
class Booking
{  
	public function __construct(Data_Access_Gateway $gateway)  
	{  
		$this->_gateway = $gateway;  
	}
	public function getRoomBetweenDates($dateFrom, $dateTo)
	{
		return $this->_gateway->getRoomBetweenDates($dateFrom, $dateTo);
	}
	public function addBooking($userId, $roomId, $fromDate, $toDate, $price)  
	{  
		$data = array(
			'userId' => $userId,  
			'roomId' => $roomId,
			'fromDate' => $fromDate,  
			'toDate' => $toDate,  
			'price' => $price,  
		);  
		$bookingId = $this->_gateway->insert('bookings', $data);  
		return $bookingId;  
	}  
}

Domain Model

Domain Model organizes domain logic into well defined domain entities that contain both behavior and data. Usually each entity class represents a single entity in the data layer. Domain Model creates a hierarchy of inter connected objects that interact with each other by triggering behaviors on each other. Domain Model shines over Transaction Script and Table Module when it comes to handling domain complexity. It enables the full power of object oriented programming and all available design patterns. Even though Domain Model may sound like a silver bullet to all software development problems it is not. Learning to design applications using Domain Model requires a “paradigm shift” to start looking for entities and behaviors instead of looking for routines. The main downside of Domain Model is the way it works with relational databases. To compare I would like to quote Martin Fowler:

In many ways Domain Model treats the relational database like a crazy aunt who’s shut up in an attic and whom nobody wants to talk about.

Domain Model tries to be data layer agnostic. This is what object relational mappers also known as ORM’s as Hibernate try to solve by hiding the data access layer away.

To show an awkwardly simple example of Domain Model let’s re-factor the Table Module approach. To keep the example simple I’ll ignore the data access layer.

class Hotel
{  
	protected $_hotelId;
	protected $_rooms;
	public function bookRoom(User $user, $fromDate, $toDate)  
	{  
		$room = $this->_getRoomBetweenDates($fromDate, $toDate);
		if (is_null($room)) {  
			return false;  
		}  
		$booking = $room->bookRoom(User $user, $fromDate, $toDate);
		return $booking;  
	}
}
class Room
{
	protected $_roomId;
	protected $_bookings = array();
	public function bookRoom(User $user, $fromDate, $toDate)
	{
		$days = $this->_getAmountOfDays($fromDate, $toDate);
		if ($days < = 7) {
			$booking = new Booking($user, new ShortBookingStrategy($user, $days));
		} else { 
			$booking = new Booking($user, new NormalBookingStrategy($user, $days));
		}
		return $booking;
	}
}
class NormalBookingPriceStrategy extends BookingPriceStrategy
{
	public function getPrice()
	{
		$price = $this->_days * 80;
		if ($this->_user->isLoyal()) {
			$price = $price / 2;
		}
		return $price;
	}
}
class ShortBookingPriceStrategy extends BookingPriceStrategy
{  
	public function getPrice()
	{
		return $this->_days * 100;
	}
}

As you can see there is an instant explosion of classes and the data access layer is out of the picture. Responsibility to efficiently load and keep track of loaded entities is left to object mappers like Hibernate.

The End

Everyone of these domain model patterns have their benefits and downsides. It takes experience to be able to decide which approach to take. For those who are new to Domain Model it is advised to have an experienced team member who is able to guide you through it. While Transaction Script or Table Module can seem like a good solution at some point it may not be as effective later on. It is important to recognize when a different domain model approach might work better. It’s been a long ride for me. Through the years I’ve learned a few things about designing software but I still don’t feel very comfortable writing about it. I would love to hear feedback from you how this article and these examples could be improved to enable better understanding between the different modeling approaches.

, , , Hide

Jan/10

17

Creating websites with Drupal cons and pros

Recently I’ve set myself of a new journey since I’ve decided to help my friend’s business to  battle the crisis back home by creating them a new website. It’s a bit ironic but I didn’t know where to start, because at work I usually work with custom made websites which very rarely use a content management system.

The content management system I’ve chosen to use is Drupal - a widely adopted opensource content management system written in PHP. It has a vast community and enormous amounts of modules developed by other people. It took me about a week’s worth of evenings to get to know the system and launch the website. Here are the steps involved to create a Drupal website:

  • Install Drupal. The installation was really easy and simple. Put it on your webserver, access the website, follow an easy guide and you’re done.
  • Configure Drupal. To a new user Drupal configuration may seem hectic or chaotic at first. It may take a while to get the hang of things. Figuring out how to change website information, setting up menus, changing themes, hiding things that you don’t want to display.
  • Pick a theme. It’s generally better to pick an already made theme and modify it to fit your needs. Themes are designed to integrate with Drupal nicely. They will likely look the same on all popular browsers, will be HTML standard compliant, optimized for SEO and may even be optimized usability wise. I found it very easy to pick a theme using theme garden.
  • Install modules. Drupal is a modular content management system and comes with a few useful bundled modules it self. One of the strongest Drupal’s key points is that it has a vast community actively developing modules for it. If you ever need to do something on your website most likely there is a module to do it.

More about modules

Drupal has many useful modules such as Blog, Comments, RSS, Forum, Search, Localization, Content categorization. But the true power lies in modules developed by the Drupal community. A few examples:

  • CCK. Content construction kit allows you to add custom fields to content nodes.
  • Views. One of the most essential modules for Drupal. Alows to change website’s representation in many ways.
  • Pathauto. Allows to configure how website’s URL’s are constructed. A very powerful module for anyone interested in SEO.
  • Nodewords. Allows to change meta tags. Very useful to provide custom meta descriptions for content pages. Descriptions are important for SEO.
  • Page Title. Another useful Drupal SEO module that allows to provide custom page titles.
  • Lightbox2. Very nice plugin to display images on the website. Also supports slideshow.
  • Wysiwyg. Allows to replace a simple content text editor with a rich text editor of your choice.
  • Node Gallery. A nice lightweight image gallery for Drupal. Still in alpha stages but very easy to use and provides lot’s of configuration. Integrates with Lightbox2.
  • Backup and Migrate. Creates scheduled website backups in case there’s an emergency.
  • And many other modules

Pros and Cons of Drupal

Drupal has many pros:

  • Extremely easy to install on any webserver.
  • Has a vast community developing modules and providing technical help.
  • Has a huge amount of freely available themes to pick from.
  • Is very well adopted and maintained which means that bugs are fixed, security patches are released and new cutting edge features are always on the horizon.
  • Drupal is fast. Maybe it’s not the fastest content management system in the world but it certainly is fast. It’s very easy to set Drupal cache settings which give an immediate boost to the website.
  • It’s relatively easy to set up a website that is Search Engine Optimized aka SEO.

Like everything in life Drupal has a few cons:

  • For new users Drupal may be overwhelming somewhat chaotic and hectic. It’s still very easy to set up a theme and enter content. But you may have to scratch your head for a while how to add localization support to Drupal.
  • Drupal is quite old and even it’s actively developed lot’s of it is written in procedural PHP. Which isn’t necessarily a bad thing, but in some way means that it’s not a top cutting edge software modelling masterpiece.
  • Even though Drupal has a huge community which develops modules for it some of the modules don’t have very good documentation. More often than not these are the less used ones. It’s not Drupal’s fault but it’s still confusing and somewhat frustrating to try and figure out where and how you can configure some module you’ve just installed.

All in all I’m happy with Drupal and I think it’s an amazing project and I’m giving my thanks to the Drupal community for all the greats things they are doing.

, , , Hide

Zend Framework 1.8 book As I mentioned earlier guys from Packt publishing asked me to review a recently published book Zend Framework 1.8 Web Application Development. The title says it all - it’s a book about designing and developing PHP web applications using Zend framework.

This book doesn’t require the reader to be familiar with zend framework and explains all concepts in proper detail, though it will be easier to read the book if the reader is familiar with the framework and/or has experience with MVC and OOP in general. This book should be interesting to all developers who design and develop day to day web applications using MVC frameworks or not yet familiar with them as it may improve their insights towards web applications modelling, testing , optimizations and more.

Even though I am fairly familiar with the framework I found the book to be an interesting, easy read, plentiful of examples explaining the intricacies of the framework.

The first though a very important chapter teaches the concept of bootstrapping using Zend_Application and shows how to write and run a simple hello world program using controllers and views. As well it introduces the use of controller utility methods such as _getParam(), _forward(), _redirect(), action helpers, view helpers which are very valuable and a lot of developers miss them entirely. This chapter also shows the proper use of the response object which also tends to get forgotten.

The second chapter dives straight into the Front Controller pattern explaining how the framework routes, dispatches requests and responds to the client. I have never been bothered to understand the whole thing and was quite surprised to see how simple it all is. It is worth mentioning that this chapter explains in great detail how the router and various routes work and how elegantly it integrates with Zend_Config. Last the chapter covers the request object and it’s external API which provides lot’s of valuable functionality.

From the third chapter author Keith Pope starts building the main application of the entire book, the Storefront. It’s a relatively simple “real life” application that serves the purpose of being an online products catalog. This chapter shows how such an application is structured on a file system and bootstrapped and configured.  Even more the chapter covers the creation of Zend_Log and various logging writers and database profiling. Extremely valuable features that not many developers know of. If every zend framework application would start as the chapter describes I believe a lot more developers would be eager to start their IDE’s 9:00 AM straight.

Next is my personal favorite chapter - Models. Zend Framework does not have a base Model class and there’s a pretty good reason why it doesn’t. Models are specialized for a certain business task and as such it is arguably impossible to make a generic model implementation that would fit all sizes well. It then might raise a question what’s there to read about? It is my personal belief that web applications modelling has lost focus during the years by the ever growing development community. Developers got their minds focused on the next “new” thing. Let it be template engines, ORM’s, rise of active record and ruby on rails, ajax and javascript frameworks. While the majority of the models “out there” are deeply crippled. Hundreds of books were written explaining how to manage the complexity of the problem so a single chapter is a mighty challenge. I believe the author made a great choice by explaining the concept of the fat model, skinny controller, explaining the benefits composition over inheritance, data access layer separation from the business layer and my deepest respect for introducing domain model design, Martin Fowler’s book Patterns of Enterprise Application and Eric Evan’s book Domain Driven Design also known as DDD.

Next five chapters describe the implementation of the Storefront application. Each chapter highlights a major component of the framework. Use of resource autoloaders, plugins, Zend_Form, Zend_Auth, Zend_Acl. Before saying anything else it is very important to say that books rarely ever show hardcore “real life” applications as examples. Even Fowler himself likes to skip certain topics like validation in certain sections of his famous book just because they complicate things too much. This book is no exception to the rule. It’s a pretty straightforward application. There isn’t a single join to another table or a GROUP BY statement in SQL, forms implemented with Zend_Form are rather simple with little if any javascript / ajax. I found it a bit disturbing that class create other classes having both business and factory logic. One of the ugly examples was where a getPrice() method on a product model creates it’s own Taxation service which could not be mocked if that class would need to be unit tested. In most of the cases author provides injection methods for unit testing but I would argue that it does not show class dependencies explicitly which is very valuable for unit testing. Besides that I really enjoyed how the author decided to go with ACL in the domain layer. This would more often than not be implemented in the controllers making the model tightly dependent on the controllers. All in all keeping in mind that it’s a tutorial application introducing the framework I’m highly satisfied of it’s overall quality. Repeating myself. If every zend framework application would be so well written..

Another chapter worth mentioning is regarding optimizations. I was surprised to learn about such things like plugin loader cache, table gateway metadata or various Zend_Cache frontends which I have never bothered to look up. Not to mention widely known tricks using APC, stripping zend framework of all requires and setting up an optimized include path.

And last but not least again one of my favorite topics - testing. I strongly agree with Misko Hevery that test driven development is a skill. It’s definitely not easy to start or learn. One would fool himself to think otherwise.  This topic deserves many books of it’s own. I can only share from my own experience - once I started unit testing applications that I work with, I have never looked back. This chapter explains different types of testing, shows how to setup PHPUnit and provides examples of controller testing using Zend_Test. I believe this chapter deserves more attention on how to do testing with a database in mind, debugging failing controllers, avoiding complicated mocks, implementing continuous integration. But again it is worth to keep in mind that the book is about Zend Framework and not testing in general.

All in all I enjoyed reading this book. I would and will recommend it to my colleagues and friends. I hope that this hopefully not too boring review convinced you to buy the book and learn something new. Once again - big thanks to Packt Publishing for a free book. Happy reading. Over and out.

, , , , Hide

Oct/09

18

PHPNW09 Conference

This is my summary of PHPNW09 conference that I was lucky to attend. This was my first real conference and I was blown away. Talks that I enjoyed most are the keynote about the uncertainty principle, Lorna’s talk about the Joel Test and Rob Alen’s talk about project management. It was also very interesting to hear about the state of the PHP project and it’s internal development teams. Did you know that PHP has only about 100 active developers of whom only ~10 are core developers?

The event itself was perfectly organised. I don’t have a single complaint. Timings were perfect and don’t get me started about the food. It was delicious!

I also had an epic opportunity to see how Microsoft fails to demo their flowchart software which was highly amusing. Though I feel highly thankful to these guys because they were the major sponsors of the event not to mention their help on PHP windows builds.

In the evening we were invited to a SUN sponsored bar where I had an opportunity to meet and chat with really interesting people. Met a PHP star Derick Rethans, had a really great conversation with the event’s organizer Jeremy Coates and even met people from my own homeland.

All in all this was a great experience and I’m definitely coming back next year. There are also other conferences coming up in Barcelona and London which I hope to attend.

, , Hide

Apr/09

7

Internaly GoogleTalk uses XMPP messaging protocol. XMPP - The Extensible Messaging and Presence Protocol. Often also called as Jabber. Since it’s an open protocol means it’s possible to develop your own clients to connect to other XMPP servers.

There are quite a few xmpp libraries that provide client functionality. The one I tried myself is XMPPHP. It’s usage is really simple. For example to send a message you would do something like this:

require_once('XMPPHP/XMPP.php');
$conn = new XMPPHP_XMPP('talk. ', 5222, '[email protected]', 
'password', 'xmpphp', 'gmail.com', $printlog = false, 
$loglevel = XMPPHP_Log::LEVEL_INFO);
try {
    $conn->connect();
    $conn->processUntil('session_start');
    $conn->presence();
    $conn->message('[email protected]', 'Hi!');
    $conn->disconnect();
} catch(XMPPHP_Exception $e) {
    die($e->getMessage());
}

I find this to be quite valuable. Who these days does not keep their IM live all the time? I imagine it’s like a cellphone. Meaning you can use it for many different services.

For example I developed a small application that checks if every one of my collegues is “Working on a task” in FogBugz and if not it sends an automated message to them to remind them that they should select a task they are working on. I also have a small tracker that tracks a local torrents network looking for high rated IMDB movies. I have an idea that it would be nice to integrate my tracker with GTalk so that it would inform me when a new episode of House MD is available or a new highly rated movie appears. The sky is the limit ;)

, , , , Hide

Mar/09

31

PHP XML formatter tool rewrite

A while ago I blogged about an XML Beautifier Tool which is able to tokenize an XML string and output it in human readable format. Strangely enough I noticed that I get quite a few pageviews from people searching for such a tool. Though this tool may be useful to a lot of people I think it is flawed and has serious issues with formatting, speed and memory consumption.

This inspired me to write a new version of XML formatter. It’s based on a SAX parser which is kind of “ugly” to implement and build around but because of it’s event based nature it’s super fast and has a very low memory footprint. The new version of the formatter shouldn’t peak higher in memory than 200 - 300kb even when the XML files start to weight over a megabyte. It also should not have any problems with indentation because it no longer tries to tokenize the XML itself and uses libxml to do the job. I also tried to make the tool documented and extendable.

It’s usage is really simple. All you have to do is initialize an object of XML_Formatter by passing an xml input stream, xml output stream and an array of options and call the format method. You might wonder why it requests input and output streams instead of a file name or a string. It does that to avoid high memory consumption. Here’s an example of how one might use XML_Formatter:

require('XMLFormatter.php');
$input = fopen("input.xml", "r");
$output = fopen("output.xml", "w+");
try {
    $formatter = new XML_Formatter($input, $output);
    $formatter->format();
    echo "Success!";
} catch (Exception $e) {
    echo $e->getMessage(), "\n";
}

Nevertheless this tool is quite powerful in what it can do  (I was able to format other website’s XHTML or tidied HTML sources) it also has some problems which are not actually related to the formatter but may seem odd to the user. The PHP xml parser does not understand such entities as   or unsescaped ampersands like in ?x=1&y=1. So it’s the user’s responsibility to provide “correct” XMLs to the formatter.

Other than that I hope it will prove useful to someone. Download the latest version of the XML_Formatter.

, , , Hide

Mar/09

20

Sample PHP MVC application

Every web developer probably at some point heard something about MVC unless he or she was living in a cave. I definately have heard and read a lot about it. I won’t probably lie too much to say that most people know that MVC is the nowdays defacto design pattern for web applications. Atleast for PHP it is.

If you have ever had interest in design patterns and did some research on them you may know that design patterns may be interpreted and implemented different every time one tries to. And MVC is no exception to this rule. In my own career path I have seen many projects that claim to implement the MVC design pattern. And if it actually doesn’t - it may be called a hybrid of MVC. As ridiculous as it may be I think because of the MVC hype and everyone trying to be able to claim “yes we use MVC” it is one of the most misunderstood patterns of them all. And because of this … There are a LOT and i mean a LOT of articles and blogs and forums trying to explain MVC the way it should be.

And I myself have read a lot of versions of these blogs and articles. And to be honest I couldn’t answer to you for example what a controller should do and should not do. Well ofcourse I know it shouldn’t contain any business logic. If you would try to research that you would probaly find people saying that the controller should initiate the model, do something with the model and pass the result to the view and render it. You can even find some examples..

But to some extent I find it all synthetic and not very realistic. Most examples are of the level of Hello World program. I think the devil is in the details. If you would try to find any sample php mvc applications you probably wouldn’t find much. There are a few very simplistic sample MVC projects but I don’t find that to be an eye opener that goes deep into details.

I think the PHP community needs such an example. I believe Zend Framework is a great start for MVC. But it isn’t enough. It still doesn’t show you how a real life model or controller would look like. What each part of MVC would do and would not. I believe that one good example is better than a thousand words. I feel trully interested to try and find the “Equilibrium” of the famous MVC design pattern. Don’t you?

, , , , , , Hide

Mar/09

5

Making your life easier with FirePHP

I have been a user of FireBug for quite a long time and it saved me a lot of hours of pain debugging AJAX applications. When I see developers trying to figure out why their AJAX applications are not working without using FireBug it sometimes looks like an inexperienced woman trying to park a car without any luck whatsoever.

And then recently i found FirePHP while reading php|architect and it seems to me a such a nice tool it’s well worth to blog about it. If you want to debug ajax applications with FireBug you must do your own variable dumps which break the output. While FirePHP is capable of sending all this data through http headers without breaking the response of your json, xml, image responses. It also provides a very nice library for logging various stuff.

One of the things I really liked is the ability to easily view backtraces through FirePHP. Though it seems to me it can only view backtraces of your own defined local php function calls. It would be nice to see FirePHP integrated with Xdebug. Then it could do a full stack trace with all the parameters involved and even memory usage.

I also love the fact that there is a Zend_Log_Writer for Firebug. It also can send information to firebug console. But it’s not as “sweet & cute” like FirePHP.

I believe that FireBug, FirePHP, Xdebug are the must have tools for every php web developer. It saves more than a reasonable amount of time spent debugging.

, , , Hide

Jan/09

23

Anti Asynchronous AJAX calls and PHP sessions

Few days ago we found a strange bug in one of our applications we are developing. We were creating a certain feature that made up to 2 - 6 asynchronous ajax calls when certain pages were hit. Those ajax requests contact various services providers and it takes a different amount of time for each one of them to respond. We found it odd that none of the calls were actually asynchronous and they were starting to execute one after another. For example we fire 3 asynchronous ajax calls:

  • ajax call 1 takes 2sec.
  • ajax call 2 takes 3 sec. but responds after 5 sec. only
  • ajax call 3 takes 4 sec. but responds after 9 sec. only

It didn’t took long to figure out that it had something to do with our php handler scripts that are accepting these ajax calls. We found out that the session_start() function call did not allow these scrips to run in paralel. It soon became clear that two php scripts can’t use the same session in paralel because without locking they could both do some changes to session and one script would override other script’s changes.

Turns out there is a function for exactly these kinds of situations in PHP and it’s named session_write_close(); It’s purpose is to write session data and end session. After it is done writing it releases the lock for other scripts to use the session. So now our php handler scripts initialize the session to check that the user is logged in, writes the session changes and ends it, contacts services providers and then starts the session again to make the final session changes. That way one script doesn’t hold the session locked for it’s whole execution time.

, , , , Hide

Dec/08

31

Benchmarks battle: Yii vs. Zend Framework

While browsing through planet-php.org like every morning I’ve found this blog post promoting Yii framework. Interested I took a look at Yii benchmarks page and got really surprised.

To be honest benchmarking frameworks on a hello world application is a bit unfair. A hello world application requires very little complexity from the the framework. Zend Framework is a very powerful framework that has many strengths. A test should do something realistic. For example connecting to a database, having a configuration file, properly rendering a view, having a model to retrieve data, doing something with it, rendering a layout, trying some plugins or other components like pagination. It requires more work to do such applications, but that is a good way to do a fair benchmark.

Not related to benchmarking but I couldn’t help but notice that Yii benchamarks die in controller actions. It is not best the best thing to do. It does not allow the framework to completely shutdown and do whatever it has to do. For example executing post dispatcher methods.

The benchmarks say that Yii 1.0 is 800% faster with APC than ZendFramework 1.7.2. That is trully amazing. A huge difference. And.. I don’t really believe it is true. So let’s run the same benchmark on our own metal ;)

Let’s start with server configurations.

Yii server:

Operating System: Red Hat Enterprise Linux Server release 5.2
Web Server: Apache httpd 2.0.40
PHP: 5.2.6, any non-essential extensions are disabled
CPU: Dual Intel Xeon 3.2GHz
Main Memory: 2GB
Hard Drive: 73GB 15K RPM SCSI/SAS HDD

Our server:

Operating System: CentOS 5.2
Web Server: Apache/2.2.3 Default configuration
PHP: PHP Version 5.2.6 Default configuration + APC
CPU: Intel(R) Pentium(R) 4 CPU 3.00GHz
Main Memory: 1GB
Hard Drive: 250GB 7200 RPM SATA2

As you can see there is no big difference. Actually our server is slower :( Less CPU power, less RPMs on HDD, more not needed modules and extensions enabled, less memory.

I used the same APC settings as the Yii folks.

apc.enabled=1
apc.shm_segments=1
apc.optimization=0
apc.shm_size=32
apc.ttl=7200
apc.user_ttl=7200
apc.num_files_hint=1024
apc.mmap_file_mask=/tmp/apc.XXXXXX
apc.enable_cli=1
apc.cache_by_default=1

I’ve downloaded Yii 1.0 and zend framework 1.7.2. I’ve setup the same applications the Yii folks provide. Except I’ve removed the die and replaced it with an echo. And changed the ZF bootstrap file to work in no view renderer mode. The bootstrap file looks like this:

set_include_path(dirname(__FILE__));
require_once 'Zend/Loader.php';
Zend_Loader::registerAutoload();$front = Zend_Controller_Front::getInstance();
$front->addControllerDirectory(dirname(__FILE__)."/application/controllers", 'default');
$front->setParam('noViewRenderer', true);
$front->dispatch();

And then I ran the same AB test: “ab -t 30 -c 10 URL” as the Yii guys. I also want to note that I ran the tests a few times to warm up the APC cache. Let’s look at the results:

  • Zend Framework 1.7.2: 184 RPS (requests per second)
  • Yii 1.0: 275 RPS
  • Yii 1.0 with yiilite.php: 235 RPS

And now lets evalue these test results:

  1. Even on a slower machine ZendFramework is more than 3 times faster with APC than in the Yii benchmark. (strange)
  2. In comparison Yii is not 800% faster than ZF like shown on the Yii benchmark page.

It’s possible I’ve made a mistake somewhere. It would be nice to see more people testing this.

, , , Hide

<< Latest posts

Older posts >>

Find it!

Theme Design by devolux.org