signalkraft

Real-World Examples of PHP5.3

Without further ado, here’s some cool stuff that only works in the latest big release of PHP:

Adding Data to an Array
<?php
	
	$blogPosts = getBlogPosts();
	$postsWithPictures = array();
	
	// The old way...
	foreach($blogPosts AS $key => $post)
	{
		$postsWithPictures[$key] = $post;
		$postsWithPictures[$key]['pictures'] = getPostPictures($post['id']);
	}
	
	// ...the anonymous function...
	$postsWithPictures = array_map(
		function($post) {
			$post['pictures'] = getPostPictures($post['id']);
			return $post;
		},
		$blogPosts
	);
	
	// ...and the lambda:
	
	$addPictures = function($post) { 
		$post['pictures'] = getPostPictures($post['id']); return $post; 
	};
	
	$postsWithPictures = array_map($addPictures, $blogPosts);

The final verdict on performance is still out — in theory the procedural style of foreach loops is slightly quicker than array_map, as the latter adds a function call to every iteration. We’re talking milliseconds here, and in this example getPostPictures() would probably slow down all three examples to an equally slow pace.

Closures as Function Arguments

Imagine you have a HTML helper function that generates anchors from a route…

<?php echo anchor('Blog/archive', 'Archive'); ?>

…using your framework’s Router library the result might look like this:

<a href="http://blog.com/myblog/archive.html">Archive</a>

In one particular case you need to alter the generated link slightly. You could hardcode that specific case into the function itself and add another parameter, or you could add a much more future-proof method of changing the HTML layout with a third, optional Closure argument:

<?php
	$wrapper = function($route, $name) {
		return "<span target=\"$route\">$name</span>";
	}
	echo anchor('blog/archive', 'Archive', $wrapper);
?>

The anchor function definition could look like this:

<?php
function anchor($route, $name, \Closure $wrapper = null) {
	if (is_null($wrapper)) {
		$wrapper = function($route, $name) {
			$href = MyFramework::getRouter()->resolve($route);
			return "<a href=\"\">$name</span>";
		}
	}
	return $wrapper($route, $name);
}
?>

This means you now covered all possible usage scenarios involving the layout of the generated HTML.

The typehint in the 2nd line (\Closure) “hints” at another fantastic new feature in PHP 5.3 — namespaces.

You should check out the latest development in Doctrine 2.0 for some real-world usage of namespaces.