ObservableTrait – Experiment with PHP 5.4

Posted on March 3rd, 2012 in PHP, Web Development by Greg

PHP 5.4 was released this week, and one of the biggest new capabilities from a language perspective is traits, called mixins in some other languages. Traits are basically a way of creating a set of reusable methods and properties and adding them to class, almost like copy paste. In a way this is like inheritance, but a class can use multiple traits to add multiple capabilities. Whereas with inheritance you say something like ‘a Dog is an Animal’, with traits you say ‘a Dog can be observed’.

To try out traits I took inspiration from JavaScript, a language that I’ve been using quite a bit recently. Client-side javascript for complex applications is very event driven and accordingly makes heavy use of event listeners – both DOM events and custom events. One approach that I’ve been impressed with is Sencha’s Observable class/mixin that allows classes to easily fire events and notify any listeners without tightly coupling the listeners and the observed.

While PHP is significantly less event driven (user input only comes at the beginning of a script), I thought that implementing a similar Observable mechanism would be a good way to try out the new feature. I’ve added the trait to my growing library of utility classes on Github. Here’s how it works:

1. A class uses the ObservableTrait and then fires events whenever an important event occurs:

Class Dog {
	use gUtils\ObservableTrait;
	public $name;
	public function __construct($name) {
		$this->name = $name;
	public function bark() {
		echo "woof woof\n";
		$this->fireEvent('barked', $this);
	public function rollOver() {
		echo '(' . $this->name . " rolls over)\n";
		$this->fireEvent('didTrick', $this, 'roll over');
	public function shake() {
		echo '(' . $this->name . " shakes hands)\n";
		$this->fireEvent('didTrick', $this, 'shake hands');

The calls to fireEvent include the name of the event, and any additional parameters that should be passed to any listener.

2. On instantiation of an object, listeners can be attached to the object to be notified when particular events occur:

$fido = new Dog('Fido');
$listeners = $fido->addListeners([
	'barked' => function($dog) {
		echo 'Shhh ' . $dog->name . "\n";
	'didTrick' => function($dog, $trickName){
		echo 'Good dog, ' . $dog->name . " - I love it when you {$trickName}\n";
$fido->bark(); // Shhh Fido
$fido->rollOver(); // Good dog, Fido - I love it when you roll over
$fido->shake(); // Good dog, Fido - I love it when you shake hands
echo "stopped listening for a while\n";
echo "listening again\n";
$fido->bark(); // Shhh Fido
echo "removed bark listener\n";
$fido->rollOver(); // Good dog, Fido - I love it when you roll over

And that’s about it – you can:

  • Add Events
  • Add Listeners (one at a time or multiple)
  • Remove Listeners (one at a time or multiple)
  • Stop throwing events
  • Resume throwing events
  • Remove all listeners

So take a look and let me know what you think…

InputValidator – Simple Input Validation for PHP

Posted on December 26th, 2011 in PHP, Web Development by Greg

I recently needed a library for validating form input and everything seemed either verbose or required a huge number of files and libraries to be included. Here’s what I was looking for:

  • Easy to include in projects without having to change include paths, mess with auto loaders, or include other frameworks
  • Something that minimized the amount of validation code that needed to be written, preferably with a fluent interface
  • Ability to generate error messages that can be shown to the end user
  • Ability to transform data to data types needed by the rest of the script
  • Capability to validate against arbitrary regexes
  • Capability to validate against closures or other external functions

I couldn’t find exactly what I was looking for, so I decided to write it myself. I added the result, InputValidator, to my gUtils collection of PHP classes on Github. InputValidator is a standalone script for validating user input from forms or other sources.

Everything is in a single file, making it easy to include in any (PHP 5.3+) project. Here’s some example usage:

// this could be from $_POST
$data = array(
  'name' => 'Greg Neustaetter',
  'email' => 'greg@emailaddress.com',
  'website' => 'http://www.gregphoto.net',
  'favoriteNumber' => 'xyz',
  'date' => '11/11/2011'
// pass in the data to be validated
$v = new gUtils\InputValidator($data);
// validate each field
$v->field('email', 'Email Address')->required()->email();
$v->field('favoriteNumber', 'Your favorite number')->intRange(0,100)->toInt();
$v->field('date')->toDateTime('m/d/Y')->after(time()); // after the current time
if(!$v->allValid()) {
    echo '<pre>';
    print_r($v->getErrors()); // returns an array of errors indexed by field
    echo '<pre>';
$data = $v->getValues();  // returns an array of values indexed by field
$name = $v->get('name'); // get the value of name
echo $v->escape('name'); // escape the value of name for output with htmlspecialchars

This script would print the following error array:

    'favoriteNumber' => Your favorite number must be an integer between 0 and 100
    'date' => Date cannot be before 12/24/2011

In addition to validation the library includes a few filters to manipulate data and cast it to formats needed by your code. Take a look at the documentation on the Github wiki for a list of the 20 validators and the 8 filters.

Let me know if you find it useful or if you have any feedback…


Posted on June 9th, 2011 in PHP by Greg

RecursiveFileExtensionFilteredIterator – rolls right off the tongue, right?

Recently I had the need to find all of the files in a fairly big directory structure that were web pages – in my case, files with the .php and .html extensions. There were hundreds of directories and thousands of files to go through, so I decided to write a php script to find the files and then execute some code on the resulting files.

I abstracted out the code to find files matching a particular extension and have posted the (minimal) code on Github as RecursiveFileExtensionFilteredIterator. The 20 or so lines of code makes use of a couple of PHP’s SPL iterators including the Recursive Directory Iterator, the the Recursive Iterator Iterator, and the Filter Iterator. The result of this is a simple class that allows you to loop through a directory recursively to find only files that match a particular set of extensions, returning a SplFileInfo object for each file. Here’s a simple example that prints out all of the paths:

$path = '/path/to/starting/directory';
$extensions = array('php','html');
$files = new RecursiveFileExtensionFilteredIterator($path, $extensions);
foreach($files as $file) {
	echo $file->getPathname() . "\n";

that’s it – short and sweet.

PasswordHelper: PHP library for password hashing and more

Posted on January 19th, 2011 in PHP by Greg

Only two years since my last post :)

I was fixing up an old website I had built to improve the security and as part of that I wanted to improve the way in which passwords were stored, created, and verified for complexity. As part of this I built PasswordHelper, a small PHP library (61 lines of code) described on the overview/download/documentation/example page as follows:


PasswordHelper is a lightweight BSD licensed PHP class that has a number of password related utility functions that make it easy to:

  • Securely store passwords by hashing them with the adaptive Blowfish/bcrypt algorithm with random salt values
  • Compare user submitted passwords with stored password hashes
  • Generate random passwords
  • Validate password complexity for length and matches to a configurable set of regular expressions

The library does nothing too complex – it just makes it easy to do common things to help create more secure PHP applications utilizing existing PHP functions through a simpler API. Most of the existing APIs seem a bit…cryptic (ha ha, right?) and there are so many options and algorithms from which to choose. Choosing the ‘wrong’ algorithm for password hashing can lead to big problems, like the ability for hackers to brute force hundreds of thousands of passwords from your database in an hour.


Here’s a quick example of how it is used:

$pass = new PasswordHelper();
// Hash a password with bcrypt and a random salt before storing it in a database
$hash = $pass->generateHash('myP@ssword');
// Validate the password against the stored hash on a login attempt
if($pass->compareToHash('myWrongPassword', $hash)) {
	// password matches	
} else {
	// password doesn't match
// Generate a random password
$randomPassword = $pass->generateRandomPassword();
// Validate the complexity of a password
if($pass->checkPasswordComplexity($password)) {
	// password meets requirements	
} else {
	// password doesn't meet requirements

Check it out if you need some help with passwords in your PHP application…

Review: Balsamiq Mockups

Posted on April 22nd, 2009 in Technology by Greg

In my job as a product manager one of my key responsibilities is designing high-productivity software that is easy to use and powerful. We work in a complex domain that involves massive amount of data, millions of dollars on the line, and tight deadlines. We attack these complex software with advanced technology, masked in easy to use software.

One of the challenges with user interface development – and all software development, for that matter – is that the further down the line in development something goes, the harder it is to change. Once a developer spends days or weeks working on something the resistance becomes huge as people are attached to their work – regardless of whether it is a good fit for the customer. To counter these problems, I’m a big advocate of building mockups in order to sort out the key design issues before significant development happens.

Over the years, I’ve used the following types of tools to do this:

  • Whiteboards with digital camera snapshots
  • Pen and paper sketches scanned
  • Photoshop / image mockups
  • HTML mockups
  • PHP prototypes

I use these various tools to build mockups for a variety of applications including native windows applications, classical web applications, and dynamic ajax applications. The more complex applications become, with complex widgets such as data grids, trees, and tabs, the tougher the hurdles are to crank out a quick mockup. The other problem I’ve seen is that the closer to ‘real’ a mockup looks, the more people are going to comment on the nitty gritty details instead of focusing on the key issues of workflow and usability – just like the problem of developers getting attached to something they’ve worked on, reviewers of super realistic models seem to often just assume that they can’t question the general structure and end up commenting on alignment issues, colors, etc.

I’m always on the prowl for new tools to use in this design phase, and have recently come across a product that is becoming a great addition to my arsenal of tools: Balsamiq Mockups. Balsamiq is a lightweight tool for building wireframes/mockups that look like sketches. The focus is on rapid creation of screen mockups that are easy to make and easy to change, encouraging feedback and rapid iteration. The product is available in a desktop version and also version integrated with Wiki software like Confluence. For the past few weeks I’ve been playing around with the desktop version – their website said that they’d give a free license of the desktop version if you promised to write a review, so here I am! Here I’d like to point out some of my likes, some annoyances, some features I’d like to see, and a weird little bug I came across.

First off, here’s a sample of what a mockup looks like for a fictional, non-sense product:

Balsamiq Mockup screenshot

In a way, Balsamiq seems to be very much inspired by Microsoft PowerPoint…but in a good way. You drag shapes from a list of about 75 widgets onto a page and then rearrange, align, and change properties for the items. The big difference is in the different types of widgets that are available. There are some basic shapes, but most of the widgets are things you would see in applications, like text inputs, dropdowns, radio/checkboxes, and then some more complex widgets like tabs, trees, data grids, and iPhone widgets. The result is that you can build things fast – the mockup above took about 5 minutes to put together.

What I like

  • Easy to use – the number one feature. As mentioned, the application uses many known paradigms from existing applications such as PowerPoint and other design apps. I was able to get going without reading the manual, going through a tutorial, or getting a lesson – the application explains itself.
  • Fast – ok, this is tied for the number one feature. Because of its ease of use, it is possible to create and iterate on designs very quickly. The ‘Quick Add’ feature really speeds things up by letting you type in the name of a widget without having to find it in the mix of 75 widgets – conveniences like this can make a massive difference in productivity.
  • Just the right level of realism – the mockups definitely would never be confused with a real application, but they are clean enough that they can convey to point very well and get people to focus on the key design and workflow issues early on in product design and development
  • Advanced widgets such as tree and data table – these advanced widgets are some of the items that make it tough to build mockups for advanced apps in languages like HTML without investing a lot of effort to use libraries like extjs, jquery, or YUI.
  • Easy to export to PNG – mockups can easily be exported out to the PNG format for posting on a wiki or emailing.
  • Editable – as compared to paper mockups, these have the major advantage of being editable, so you don’t have to break out the eraser or start over from scratch.
  • Translates well to traditional webapps, ajax webapps, and desktop applications – because the application

Annoyances…or things that aren’t necessarily bugs, but would make the application easier to use if they were addressed

  • After ‘Quick Add’ clicking f2 doesn’t go into edit mode – you have to click the widget first. If you drag items from the strip they automatically go into edit mode, it would be nice to have that for the quick add as well.
  • Dragging items from the strip doesn’t show the guides unless you place the widget then drag again, whereas normally when you are dragging you see guides to help you line up widgets
  • It would be nice if there were a better way to select a set of items without moving the item beneath it. If you have 20 widgets on a dialog box and you need to shift them over to make space, in order to select them all you have to first lock the dialog box, select the items by click dragging, drag, release, and unlock the dialog. If you don’t do this then the dialog box will just be moved. This gets more confusing if you have multiple boxes on top of each other. It would be nice if there were a way to move into selection mode which would allow you to select any elements that are entirely enclosed by a bounding box.
  • Related to the previous entry, you unlock items through a right-click menu (the only usage of right-click in the app?), but if multiple items are locked in the clicked area it just shows the item type in the context menu. In some scenarios I had 3 or 4 items showing up, some of which were of the same type. It would be nice to highlight the item when hovering over it in the context menu to let you know you’ve got the right one.
  • It would be nice if the tree could user smaller fonts – some of the other widgets allow for choosing smaller fonts to fit more text, but the tree uses a very large font, making it tough to represent even remotely realistic data.

Features I’d like to see

  • Ability to click through from one mockup to another to create workflow – while I don’t need to create an entire flow for an application, if I’m mocking up a particular feature it would be useful to show 3 or 4 screens that are linked together maybe with a generated HTML files or something of the sort.
  • Ability to regroup after ungrouping items – you can group items, but you need to ungroup to make any edits (unlike PowerPoint which allows you to change text or even move sub-items), but then you don’t have an option to regroup…meaning you have to go through the same fun of locking outer elements, and reselecting.
  • Radio and Check Box controls should allow adding multiple at once similar to Dropdown – since these fields usually come with multiple entries it would be nice to have the widgets allow for adding multiple ‘rows’ of data similar to dropdowns
  • It would be nice to have right-click context menus for some operations like grouping or ungrouping
  • Layers – it might be nice to have layers (like Photoshop) to help avoid some of the issues with moving items…this would add a lot of utility but it would come with the negative impact on ease of use and ramp up time.
  • Ability to add custom widgets – it would be nice to be able to add custom widgets…now if you create a widget by composing the built in widgets you have to save it as another mockup and then select-all and copy/paste into the destination mockup – it would be nice to be able to save the widget to the strip and give it a name.
  • Favorites bar in addition to the current ‘All’, ‘Big’, ‘Buttons’ – for many projects only a small number of the widgets are necessary. In my applications I have no need for things like the iPhone widgets so they just get in the way.
  • Maybe a way to switch from click mode to select mode for selecting multiple items


  • This was a weird one. If you type ‘scro’ into the Quick Add box and click the entry for the ‘vertical scrollbar’, the horizontal scrollbar is actually added. Surprisingly, if you type in ‘scrol’ or ‘scr’ it works just fine!


Overall I really like this application – I’ve found myself evangelizing to colleagues and used it for some real feature design and have gotten good feedback from all who have seen the results. Like all software, there are many things that could be improved and there likely always will be, but it seems that the application is in active development and the focus on usability and user productivity look like they’ll keep the product on the right trajectory. At $79 I think it is a bargain and justifies its cost in hours or days of use. It doesn’t necessarily replace all of the other tools in my mockup toolbox – to get to the finer level of detail I still need to break out the HTML occasionally – but this is now usually something that happens only after I’ve validated the basic design with Balsamiq.

Rating: 8/10