There’s a programming style I rarely see in the PHP world, but one which I use from my C programming days – programming by contract. It’s a very useful technique for writing code that is demonstrably robust, and a useful compliment to unit testing with PHPUnit.

At it’s most basic, programming by contract can be summed up as:

  • Does my function or method have inputs that are acceptable to me?
  • Has my function or method generated return data that I’m happy to pass back.

PHP has the assert() method to help with this, but it is deficient and best avoided. I’d like to share the approach I’m currently using for this, to get constructive feedback on how to evolve the style further.

At the heart of this approach lies the constraint. It is a test that must be satisfied; a bit like a runtime unit test. We could do this inline:

[code lang=”php”]
function breakMe($inputData = “I am bad data”)
{
// enforce our constraint
if (!is_array($inputData))
{
throw new Exception(‘Bad data $inputData; expected array()’);
}
}
[/code]

… but the problem with that is that it quickly bulks out your code with a lot of repetitive (and avoidable) content. An ideal candidate to make into a function or a method, which could yield:

[code lang=”php”]
function constraint_mustBeArray(&$testData)
{
if (!is_array($testData))
{
throw new Exception(“Constraint failed”);
}
}

function breakMe($inputData = “I am bad data”)
{
// our constraint is now in a nice function
constraint_mustBeArray($inputData);
}
[/code]

Here, we are trading performance (the cost of a function call) for both developer efficiency and reduced future maintenance costs. In general, the trade-off is worth it; most PHP developers work on small sites where developers are more expensive than runtime costs (within reason). The time saved from proving that code is working (and bailing immediately we prove otherwise) is worth saving.

We’re also introducing an important principle: there’s no return value to check. If execution continues on the line below the call to constraint_mustBeArray(), we can assume that the constraint was passed. If the constraint failed, we let whatever exception handlers there are, well, handle it.

There’s a couple of problems with this style that have been nagging me. It has a lot of advantages, and is probably good enough, but …

  • There’s no autoload support in PHP for functions, making it a pain to work with a large number of functions in an app or framework. Life is easier if the constraints are defined as object methods instead.
  • There’s limited potential to re-use constraints once they have been defined. They have to be explicitly called. It would be great if they could be passed into (say) a data model layer of some kind as parameters, to assist in data integrity checking. (Note the common thread of making sure that bad data is detected as early as possible, and pro-actively rejected by the app).

This led me to a more OO style:

[code lang=”php”]
class MyFramework_Array
{
static public function mustBeArray(&$testData)
{
if (!is_array($testData))
{
throw new Exception(‘Constraint failed’);
}
}
}

function breakMe($inputData = “I am bad data”)
{
// constraint is now in a reusable object method
MyFramework_Array::mustBeArray($inputData);
}
[/code]

Well, it is object-oriented for sure, but it still isn’t reusable … but it could be with lambda functions …

[code lang=”php”]
class MyFramework_Array
{
static public function mustBeArray(&$testData)
{
// create the lambda function
$constraint = function($testData)
{
if (!is_array($testData))
{
throw new Exception(‘Constraint failed’);
}
};

if ($testData !== null)
{
$constraint($testData);
}
else
{
return $constraint;
}
}
}

function breakMe($inputData = “I am bad data”)
{
// we can still call the constraint as before …
MyFramework_Array::mustBeArray($inputData);

// … but we can now also do the following …
$constraint = MyFramework_Array::mustBeArray();
$constraint($inputData);
}
[/code]

This approach gives us the flexibility of both worlds … a constraint method that we can call directly, and also a constraint function that we can assign to a variable to re-use as appropriate.

There’s still a couple of weaknesses with this approach, the most obvious one to me that finding these constraint methods is no longer quite as easy (you need to know which class they are defined on), but the counter-argument is that this is why frameworks have to rely on convention.

We’re quite heavily constrained by PHP’s syntax and parser limitations here, specifically the lack of macros (which could avoid runtime costs in production environments) and that we can’t assign lambda functions to class properties at declaration time.

I’m wondering how this style of declaring constraints could be refined further. You can take it as given that we would normally throw something other than Exception. Comments welcome 🙂

Be the first to leave a comment »

Gearman is a lightweight, high-performance solution for farming out processing work from one machine to another. I’m currently looking at using Gearman as a key part of the architecture of a new web API that I’m doing the R&D for. (I’ll go into why I need something like this, and why I’ve chosen Gearman in particular, another day).

Getting Gearman up and running on Ubuntu 9.10 (Karmic Koala) is very straight-forward and only takes a few minutes, but oddly not clearly documented on Gearman’s own wiki at the time of writing.

  1. Add “ppa:gearman-developers/ppa” as a software source.
  2. sudo apt-get install gearman-job-server
  3. sudo apt-get install libgearman-dev
  4. sudo apt-get install uuid-dev
  5. pecl install “channel://pecl.php.net/gearman-0.6.0”
  6. Add a gearman.ini to /etc/php5/conf.d, with “extension=gearman.so” as the contents
  7. sudo /etc/init.d/apache2 restart
  8. Check phpinfo() to make sure gearman extension loaded

You’ll find that the gearmand process is already up and running, and listening on port 4730 on localhost. All you need to do now is to write some code to take advantage of it 🙂

Be the first to leave a comment »

Whether you’re looking at your own code before (or after!) you have shipped it, or you’re picking up someone else’s code after they have shipped it, tracking down and fixing bugs is a fundamental part of programming. If you know the code well, perhaps you can make an intuitive leap to immediately jump to where the bug is. But how do you go about tracking down a bug when intuition doesn’t help?

The nature of all code is that larger systems are built from smaller underlying systems and components. They in turn are also constructed from smaller components. The bug you are tracking down will have a cause in one of these systems, and will have symptoms that are visible in other systems. The remaining systems work fine (as far as the bug you’re looking for is concerned), and you can use this to quickly and reliably find where the bug is.

Divide your larger systems down into smaller systems at logical points, such as different server stacks, APIs, major interfaces, classes, methods and if necessary individual lines of code. Test both sides of the divide, with your tests focusing on the data that crosses the divide. If one side works as expected, the bug is not in there, and you can eliminate that side from further testing. Continue testing the remaining systems and components, which you have now isolated, by dividing those up into smaller systems and components. Keep going until you’ve reached the smallest testable system, component, unit, or lines of code that show the fault. Congratulations: you have isolated the fault.

Apart from being a strategy that allows you to work on code you’ve never seen before, this approach also has the advantage that it is evidence-based. This approach eliminates guess work, and it forces developers’ assumptions about how their code actually works in practice to be challenged. The data never lies, but be aware that it can be mis-interpreted!

The approach is iterative, and you’ll find that you’ll often go back and forth between your code and your tests, making your code easier to test and your tests have clearer and more targeted test domains and results. Fix the tests that are relevant to the bug you are tracking down, and make a list of any other issues you find along the way for you to come back and address at a later date. Stay on target, and park potential tangents and distractions for another time.

Although this sounds like a slow process when described on paper, with practice it can be executed at high speed during an emergency situation. However, the need to restore service in a timely manner isn’t always compatible with this approach, and you’re normally better off returning to your test environment where you can study the fault without inconveniencing your customers any further.

Be the first to leave a comment »

Stuart is running a course in Manchester in October immediately before the PHPNW09 conference on how to setup and organise your PHP developers to ensure things run smoothly for you and your customers, which will include looking at how to get the most out of Trac. Learn more about the course, or sign-up now.

When it’s just you, working on one project at a time, it’s easy enough to keep track of the work you’re doing and the work you still need to do to complete the job. Chances are you can keep it all in your head, or at least keep the discussions with your customer on something like Basecamp in your head. You know that you should be using source control and bug tracking because it is “best practice”, but it just seems like too much of an overhead to bother with when it’s just you. After all, you’re working on the customer’s server, and there’s no-one else editing the code anyway.

Some of the folks reading this blog post might be cringing at that, but I’ve lost count of the number of times I’ve come across professional PHP developers who work in exactly this way. Is it because they don’t know better? Maybe. Is it because it has worked okay for them up to now? For sure.

But eventually, there comes a point where one developer becomes a team of two … or more. Having a team means that you can go after larger projects … but it also means that you have to go after larger projects to pay the team. Larger projects mean more complicated requirements, multiple phased deliveries … and a larger, more demanding (and probably a more complicated) customer holding the pay cheque.

Running a team of PHP developers (like all management activity in all walks of life) comes down to three key things: direction, organisation, and supervision. Only now it isn’t just you and a customer, just a list that you can keep in your head. Now you need to keep track of a larger list, of multiple lists for multiple people to work on that need to be brought together in the end, and if anything slips through the cracks it’s your reputation on the line. Getting the customer to come back for repeat business just got a lot less easy to take for granted.

Trac and Subversion have been part of our community’s toolkit for many years now. Used correctly, you can get yourself and your customers well-organised, and grow your reputation when you grow your team. If you haven’t started using them yet, both are open-source, and well-backed with plenty of information freely available around the blogosphere on how to use them.

Or join me in Manchester in early October, where I’ll show you how they fit into an overall approach to running your team of PHP developers.

Be the first to leave a comment »

October in Manchester is home to the PHPNW09 conference. Last year’s conference was a great event, and this year’s promises to be even better. And I’m not just saying that because I’m a conference sponsor this year, honest 🙂

Immediately before the conference, I’m running a two day tutorial in the fundamentals of setting up and running a team of PHP developers, covering:

  • Keep your promises to your customers using written specifications
  • Organise your team using Subversion and Trac
  • Control quality using code reviews
  • Deliver to your customers using release management and follow-up support arrangements
  • Where to go after the course for additional learning

Places are limited to just 25 people, and there is an early-bird discount for anyone who signs up before 21st September. You can find out more on the course website, and sign-up online.

Be the first to leave a comment »

… as recommended by readers of Planet PHP 🙂

Most Recommendations

There were six Firefox extensions that folks repeatedly recommended …

  1. ColorZilla – advanced eyedropper, color picker, page zoomer and other colorful goodies.
  2. FireBug – live DOM & CSS inspector. The single greatest web developer add-on for Firefox.
  3. Live HTTP Headers – view HTTP headers of a page and whilst browsing.
  4. Web Developer Toolbar – adds a menu and a toolbar with various web developer tools.
  5. YSlow – Yahoo’s tool for analysing web pages and telling you why they are slow. Requires Firebug.
  6. Zend Studio Toolbar – debugging assistance for Zend Studio 5.5 and earlier. Isn’t mentioned on the Zend Studio 6 pages, so does that mean it is now obsolete?

… and after that, there was a lot of variety amongst the other extensions that were recommended.

Also Recommended

  1. Cache Status – easy cache status & management from the status bar.
  2. ChatZilla – IRC client for Firefox.
  3. Duplicate Tab – clone a tab along with its history.
  4. Edit Cookies – edit your cookies right in Firefox.
  5. Fasterfox – performance and network tweaks for Firefox.
  6. Firefox Accessibility Extension – test your web pages for functional accessibility features based on the iCITA HTML Best Practices.
  7. FirePHP – print to your Firebug console using a simple PHP function call.
  8. FireShot – take screenshots of web pages, and a whole lot more.
  9. Google Toolbar – Google’s famous in-browser search toolbar.
  10. GreaseMonkey – customise the way a web page displays using your own Javascript add-ons. See also Lifehacker’s Top 10 Greasemonkey User Scripts, and their Better GMail and Better Flickr add-ons to get an idea of just what can be done with Greasemonkey as a Firefox extension tool.
  11. HTML Validator – add HTML validation to your browser.
  12. IE Tab (Windows only) – open Firefox tabs using IE’s rendering engine. See also the popular IE View alternative.
  13. LocationBar2 – adds additional features to Firefox’s address bar.
  14. Lorem Ipsum content generator – Generate “Lorem Ipsum” dummy text, for when you need to fill a page with content for testing purposes.
  15. MeasureIt – draw out a ruler to get the pixel width and height of any element on the web page.
  16. NagiosChecker – see the status of your services and servers in Firefox’s status bar. You do monitor your servers, right? 😉
  17. PrefBar – power user toolbar for Firefox.
  18. Regular Expressions Tester – testing tool for regular expressions with colour highlighting.
  19. RefSpoof – easy spoofing of the HTTP referrer header.
  20. ReloadEvery – reloads a web page every so many seconds.
  21. Save Session – save your current browser windows & tabs for the next time you open Firefox.
  22. Scrapbook – save web pages locally and easily manage collections. (Like OS X web archives, as supported by Together, DevonThink, and so on, but cross-platform).
  23. Selenium IDE – record, edit and debug tests for Selenium, the automated UI testing tool for web developers. See also PHPUnit’s support for Selenium. You do have reproducible testing for you web apps, right? 😉
  24. Stylish – fix ugly sites, customise the look of your browser or mail client by using your own CSS files. Stylish is to CSS what Greasemonkey is to Javascript.
  25. Tab Mix Plus – tab management on steroids.
  26. Tamper Data – view and modify HTTP/HTTPS headers and POST parameters.
  27. TimestampDecode – treats the selected number as a timestamp and displays a decoded date/time.
  28. TitlebarTweaks – tweak Firefox’s titlebar text.
  29. User Agent Switcher – Adds a menu and a toolbar button to switch the user agent of the browser.
  30. Venkman – Javascript debugger for Firefox.

Stu’s Recommends

To round off the list, here are a few extensions that I find useful, but which weren’t recommended. If you haven’t heard of these before, give them a try.

  1. Flagfox – display a country flag in the status bar for the location of the current website’s server.
  2. Server Switcher – easily switch between development and production servers.
  3. Show MyIP – display your current external IP address.
  4. SQLite Manager – Manage any SQLIte database on your computer.

Are you a web developer? Got a favourite Firefox extension that isn’t on this list? Let us know in the comments below.

Be the first to leave a comment »

The folks from Packt Publishing recently sent me another of their books to review. If you’re not familiar with Packt, they’re a relatively new book publisher who are steadily building up quite a range of technology books on open source software, normally written by people involved or close to the software being written about. They’re like a modern day equivalent to the old O’Reilly of the 90’s, only (imho) with higher quality 🙂

A Bit About Packt

Mastering phpMyAdmin 2.11 for Effective MySQL Management by Marc Delisle is the third edition of this book, and it follows the usual pattern of Packt Publishing books. The book has clearly defined objectives on the cover, and it follows a clear progression of its chosen subject from start to end. It is well presented, with a clear layout and clean page design that makes it easy to read. The book also includes a sizeable index, something no decent technical book can be without.

I’m really pleased to see that Packt are now providing example code online for download, as well as online errata for the book. Many of their earlier books reviewed here on Planet PHP have been criticised for not doing so; it’s great to see Packt improving in this area.

No matter which Packt book you pick up, don’t let the use of language be the reason you put it back on the shelf. Most Packt books are written and reviewed by folks who don’t speak English as their first language. Once you get used to it, it’s never really a problem, but it’s worth pointing it out because if you browse their books at your local bookstore, it might put you off at first.

Introducing phpMyAdmin

If you’ve never heard of it, phpMyAdmin is (imho) one of the most important open source projects for the LAMP stack. phpMyAdmin provides a web-based admin interface for MySQL, making it extremely easy for folks new to the LAMP stack to start working with databases, and a very convenient way to avoid firing up the MySQL command-line if you need to check something or make changes to your databases.

It feels like phpMyAdmin has been around forever.

Unfortunately, it looks that way too at times. In the post Google Maps world of AJAX enabled slick and efficient user interfaces, phpMyAdmin’s usefulness can be hampered by its Web 1.0 UI, and by its continued reliance of manual configuration instead of a WordPress-like admin panel. Don’t get me wrong, phpMyAdmin is a good tool without equal atm, but it’s a workmanlike and functional tool that younger folks used to the Facebook world find a bit long in the tooth.

About The Book

Marc’s book is aimed both at folks new to MySQL and phpMyAdmin as well as experienced developers such as myself who aren’t aware of the advanced features that have been added over the years. The full chapter list is:

  1. Introducing phpMyAdmin
  2. Installing phpMyAdmin
  3. Interface Overview
  4. First Steps
  5. Changing Data
  6. Changing Table Structures
  7. Exporting Structure and Data
  8. Importing Structure and Data
  9. Searching Data
  10. Table and Database Operations
  11. The Relational System
  12. Entering SQL Commands
  13. The Multi-Table Query Generator
  14. Bookmarks
  15. System Documentation
  16. MIME-Based Transformations
  17. Character Sets and Collations
  18. MySQL 5.0 Features
  19. MySQL Server Administration
  20. Troubleshooting and Support

The first ten chapters cover the basics of using phpMyAdmin. If you’re new to phpMyAdmin, these chapters will be very helpful to you, and if you’ve been using phpMyAdmin for years, there’s still little bits in here that you might not have been aware of before now. I particularly like the way that these chapters often refer back to the configuration settings in phpMyAdmin’s config file. However, towards the end of this section, the material starts to feel a bit rushed, as if the author himself can’t wait to get onto the clever features of phpMyAdmin that have yet to come. If you’re completely new to MySQL, you might find the end of this section to be a little light on detail. I hope the next edition of this book beefs these chapters up a bit.

Like most people I know, my use of phpMyAdmin over the years has tended to stick with the basics: creating and browsing tables. I confess, it’s partly because I’ve found the phpMyAdmin UI to be more and more clunky as time has gone by, a throwback to the days before Google showed us just what could be done with Javascript and AJAX. So the second half of the book, which looks at the more advanced features of phpMyAdmin, were ones I found very educational. I had no idea, for example, that phpMyAdmin now includes an AJAX-based Designer tool, or that I can use phpMyAdmin to generate PDF documentation of my databases. I found these chapters to be very detailed and informative, although again towards the end of the second half of the book, the chapters began to feel a little rushed in places to me.

Conclusion

I have several new starters joining my team in June, and it’ll be interesting to see whether or not they find the book useful as they find their feet in their first job doing PHP web development. One thing’s for sure: I’ll have no hesitation in leaving this book out for them to read.

4 comments »

I’m still working on the next article in my series looking at PHP on servers, so in the mean time, check out this simple way to emulate Ruby’s nice way of handling separate getter, setter and state query methods in PHP:

[code lang="php"]
class Example
{
	private $canCache = false;
	private $cacheXml = null;

	function canCache($newState = null)
	{
		// check if we are querying or changing state
                if ($newState === null)
 		{
 			// we are querying
 			return $this->canCache;
 		}

  	 	// if we get here, we are a traditional getter/setter method
 		if ($newState)
 		{
 			$this->canCache = true;
 			$this->cacheXml = $this->_toXml();
 			return true;
 		}
 		else
 		{
 			$this->canCache = false;
 			unset($this->cacheXml);
 			return false;
 		}
 	}
}

$exObj = new Example();
$exObj->canCache(true);
if ($exObj->canCache())
{
 	// ... do something here
}
[/code]

It isn’t as elegant as Ruby, but it does the job, and it means that your classes don’t have to be full of seperate canDoSomething() and isSomethingAllowed() type methods. I think it makes the code that uses the object a little easier to read, and a little more intuitive. YMMV.

13 comments »
Page 2 of 212

This Month

November 2017
M T W T F S S
« Jul    
 12345
6789101112
13141516171819
20212223242526
27282930