Seamless AJAX with PRADO

The December issue of International PHP Magazine includes my latest article “Seamless AJAX with PRADO - An introduction to ActiveControls”. In this article I discuss some AJAX design patterns and show you how to make use of them in AJAX enabled components that ships with the PRADO framework.

Get your copy. I hope you like it.

Enhanced translation workflow in eZ Publish

I recently implemented a multilingual portal in eZ Publish and was faced with how to handle the translation workflow between the editors and translators. During the project I got to know the translation features in eZ Publish and got a better feeling about what’s missing. This ended up as a requirement specification that I suggested for Open Funding a few days ago. At the time of writing it has gotten 25 votes so it seems like someone agree with me. Please cast your votes if you like it :)

[Book] Managing eZ Publish Web Content Management Projects

Packt Publishing recently released their new book “Managing eZ Publish Web Content Management Projects” written by Martin Bauer from designIT.

I just went through it and this is the first book ever written about managing content management projects in general and using eZ Publish in particular. There’s a lot of technical documentation and end user documentation about eZ Publish, but there has not been any documentation for project managers besides the more general project management literature.

This book contains information on all phases in a typical eZ Publish projects life cycle. From gathering requirements, writing a project brief, planning a workshop with the client, get to the right estimates, writing the requirement specification, managing risk and find the right pricing. To managing the production using concepts from agile development, managing the information architecture with content modeling, testing, training, maintainance and support.

The nice thing about this book is that it’s not technical. It’s closely related to eZ Publish, but it also goes a far way on the content management part.

If you are a project manager responsible for any eZ Publish projects in your organization you should definitely read through this book. Developers, designers and end users can look somewhere else. However, developers and project managers work tightly together and need to understand each other. So your job as a developer is to continuously educate your project manager to understand your world - the first thing you can do is buying him/her this book :)

So, a last tip from me: Most real life content management projects is a job for “The Three Musketeers” (the designer, the developer and the project manager).

  • You need a solid interaction designer to create all the nice looking web interface so both the client and user gets happy (no one likes a bad interface even though the back-end solution is fantastic).
  • You need a good developer that now how to slice the web design, know the eZ Publish product, the template language and how to create custom extensions.
  • And you need the project manager to manage everything described in this book.

Cleaning up the Revolt source

I’m not sure if I got the latest source of Revolt, however I just cleaned up the Revolt source code so it compiles with strict mode in ActionScript 3.

Download the source code under the CreativeCommons Attribution-ShareAlike 2.5 license and compile the demo with:

mxmlc -compiler.strict Revolt.as

NOTE: The command-line compiler mxmlc comes with Flex SDK.

Sound spectrum analyzer in Flash

I’ve always been a fan of the demoscene - both the music and how visual appealing animations are created out of algorithms.

SoundMixer.computeSpectrum() in the Flex 2 SDK let you extract the current sound wave and place it into the specified ByteArray object so you easily can use it to draw your own effects.

Antti Kupila has written Revolt, an ActionScript 3 based spectrum analyzer. In addition to use the the computeSpectrum() in a sound processor class it contains drawers, scalers, effects and presets which make it really easy to create cool demos in Flash 9.

Here’s my attempt on creating a demo with Revolt. It’s built up of 4 different custom written effects put together in Revolt.

If you are interested in what’s going on in the Flash scene check out flashscene.org and AS3 Sound Spectrum Contest Results at The Flash Blog.

Webcam Motion Detection in Flash

A spectacular thing you can do with Flash is detect motion in your web camera. This is done by continuously compare bitmap data from the current image with the previous image.

Here’s a demo where you can try to head the ball - it’s true :) (you’ll need a web camera)

The whole process is described in this tutorial. I also found some other examples. If you have any references on using webcam motion detection, please post it in the comments.

Blueprint - A CSS Framework

In August, Olav Frihagen Bjørkøy launched Blueprint, a CSS framework to cut down CSS development time. Blueprint contains an easily customizable grid, some sensible and nice typography, relative font-sizes, typographic baseline, perfected CSS reset for all browsers, a stylesheet for printing and an extendable plugin system.

Check out the tutorial, some of the samples files, the coverage at Wired and Ajaxian, and an interview with Olav.

[Lessons Learned] lighttpd serving ads

The lighttpd web server is chosen by a lot of Web 2.0 services because of it’s high-speed io-infrastructure. During a recent ad campaign one of our web servers where running out of file descriptors because of too many connections and lighttpd started to reject connections. The reason for this is because of how Keep-Alive works.

Keep-Alive is an extension to HTTP, defined by the HTTP/1.1 draft, to allow persistent connections. These long-lived HTTP sessions allow multiple requests to be send over the same TCP connection and in some cases results in an almost 50% speedup in latency times for HTML documents with a lots of images.

Keep-Alive also behave differently in HTTP/1.0 and HTTP/1.1.

HTTP/1.0

If the browser support Keep-Alive, it adds an additional header to the request:

Connection: Keep-Alive

When the server generate a response to this request it also adds this header:

Connection: Keep-Alive

This way the connection is kept open and the client will reuse the current connection upon the next request. This continue until either the client or the server decides to drop the connection.

HTTP/1.1

In HTTP 1.1 all connections are kept alive, unless stated otherwise with the following header:

Connection: close

The Connection: Keep-Alive no longer has any meaning.

lighttpd configuration

The default configuration for Keep-Alive in lighttpd is (in /etc/lighttpd/lighttpd.conf):

server.max-keep-alive-requests = 128
server.max-keep-alive-idle = 30
server.max-read-idle = 60
server.max-write-idle = 360

Which means it can handle 128 Keep-Alive requests in a row on a single connection waiting 30 seconds before an unused Keep-Alive connection is dropped.

To handle more connections at once under high load you can lower both number of Keep-Alive requests allowed and the idle timeout:

server.max-keep-alive-requests = 4
server.max-keep-alive-idle = 4

Hosting an ad campaign typically means serving a lot of static Flash-files that are to be shown on external websites. The client need to perform the TCP handshake to the ad server anyway, therefor you don’t get the gain of Keep-Alive. So I found it best to just disable it:

server.max-keep-alive-requests = 0

After this configuration change and a restart of lighttpd the surveillance graphs showed that the web server could handle at least 50 times more the traffic we had. No need to think about load balancing :)

Disabling Keep-Alive like I did in this case is only suited for situations where serving these types of single requests, for web applications I would suggest tuning the values of server.max-keep-alive-requests and server.max-keep-alive-idle and see how it effects your performance.

Read more about lighttpd performance here.

WordPress upgrade

I just upgraded this blog from WordPress 1.5.2 to the current version (2.3.1). I was a bit skeptic to upgrading from such an old version but it went really well actually.

I renamed the current installation folder and unpacked the latest WordPress release. Copied the wp-config.php file from the previous installation over to the new one, and pointed my browser at wp-admin/upgrade.php to run the upgrade-script - fine the blog was up and running again.

Now what about all the plugins and the theme I used to have? I could have copied them from the previous installation, but since it’s been a while since I installed them I didn’t care and started searching for new stuff. I found Dean Lee’s Google Code Prettify for WordPress which enable syntax highlighting of code snippets using Google Code Prettify and a also changed to the Copyblogger theme by Chris Pearson.

Of course I backed up both the database and all currently running code before I even started thinking about doing this upgrade.

Thumbs up for the WordPress team!

ORM the manual way

Kore Nordmann’s post “Why Active Record sucks” explains some of the issues you get by using the popular Active Record pattern for ORM purpose in more complex situations.

“AR is just a wrapper for database access and not appropriate as an ORM. Used carefully, or with very simple applications it really may proof useful.”

I often find myself considering an ORM tool when I start working on a new database library for a client. But every time I fall back to the approach I’m most familiar with and know would give the best performance and the best API design - do it myself.

I normally use a simple solution using the Singleton pattern for managing the database connection, the Value Object pattern for all business objects and the Data Mapper pattern to manage the mapping between business objects and the database schema. It’s as simple as that – handcrafted and no magic going on.

Here’s a simplified directory layout:

lib/
  client/
    trunk/
      src/
        DataMapper.php
        ValueObject.php
        Singleton.php
        ClientSingleton.php – extends Singleton
        Product.php – extends ValueObject
        ProductMapper.php – extends DataMapper
      tests/
        ProductMapperTest.php

I tend to use a set of abstract classes to more easily follow the patterns used. The following sections shows an example of each of these classes.

Singleton

“A class that can be instantiated only once.”

abstract class Singleton {
	private static $instance;

	private function __construct() {}
	private function __clone() {}
	abstract public static function getInstance();
}

A simple implementation of this class could look something like this:

class ClientSingleton extends Singleton {

	public static function getConnection($hostname='',$database='',$username='',$password='') {
		if(!parent::$instance) {
			parent::$instance = new PDO("mysql:host={$hostname};dbname={$database}",$username,$password,array());
		}
		return parent::$instance;
	}

	public static function getInstance() {
		return self::getConnection();
	}
}

Assuming you have your connection settings in a $config-array you can initialize the singleton in the start of your script:

ClientSingleton::getConnection($config['db.hostname'], $config['db.database'], $config['db.username'], $config['db.password']);

When the connection is set up all mapper classes can get the database connection by calling ClientSingleton::getConnection().

The Value Object

“An object whose conceptual identity is based on a combination of values of its properties.”

class ValueObject implements ArrayAccess {
	public function __get($name) {
		$getter = 'get'.$name;
		if(method_exists($this, $getter)) {
			return $this->$getter();
		} else {
			throw new Exception("Undefined property: $name");
		}
	}

	public function __set($name, $value) {
		$setter = 'set'.$name;
		if(method_exists($this, $setter)) {
			$this->$setter($value);
		} else {
			throw new Exception("Undefined property: $name");
		}
	}

	// functions to implement ArrayAccess
	public function offsetExists($offset) {
		return isset($this->$offset);
	}

	public function offsetGet($offset) {
		$getter = 'get'.$offset;
		return $this->$getter($offset);
	}

	public function offsetSet($offset, $value) {
		$setter = 'set'.$offset;
		$this->$setter($value);
	}

	public function offsetUnset($offset) {
		$setter = 'set'.$offset;
		$this->$setter(null);
	}
}

I find it useful to be able to access data inside a value object in various ways. Having these methods in place and given the following Product class:

class Product extends ValueObject {
	private $id;
	private $name;
	private $attributes;

	public function __construct() {
		$this->id = 0;
		$this->name = '';
		$this->attributes = new ArrayObject();
	}

	public function getID() {
		return $this->id;
	}

	public function setID($value) {
		$this->id = $value;
	}

	public function getName() {
		return $this->name;
	}

	public function setName($value) {
		$this->name = $value;
	}

	public function getAttributes() {
		return $this->attributes;
	}

	public function setAttributes($value) {
		$this->attributes = $value;
	}
}

I can set values with:

$product->setName("One name");
$product->Name = "Another name";
$product['Name'] = "A third name";

and get values with:

echo $product->getName();
echo $product->Name;
echo $product['Name'];

I also find it very useful to use the ArrayObject from SPL to do stuff like:

$product->Attributes['weight'] = "2.8 kg";

or:

foreach($product->Attributes as $key => $value) {
  echo "$key: $value\n";
}

The Data Mapper

“Moves data between objects and a database while keeping them independent of each other and the mapper itself.”

abstract class DataMapper {
	abstract public static function findByID($id);
	abstract public static function save($object);
	abstract public static function delete($object);
	abstract protected static function insert($object);
	abstract protected static function update($object);
}

These are just the basic set of methods I use in my data mappers. The save() is just a proxy for either insert() or update(). And I always end up with a few more finder methods for various purposes.

I hope you find some of this useful. This approach has at least helped me a lot. By doing ORM this way you are able to manage both domain-driven design and database-driven design and twist them both in the way you want.