All in the <head> – Ponderings and code by Drew McLellan –

What's In Your Utility Belt?

Every developer has frustrations with the language they use. They find that there are no neat inbuilt ways to do what for them are common tasks, or that the inbuilt ways don’t work quite as they’d like. So over time, you start building up a file of little miscellaneous general-use utility functions that get carried around from project to project. Some of it you will have written yourself, other bits and bobs you may have picked up from colleagues or around the web.

I work in PHP, so I have Util.class.php which I carry around, modifying as I go. I throw any functions I want to the class as static methods, and then just use Util::my_function() throughout my app and let the autoloader take care of the rest.

Simply because I think that it’s the sort of thing that’s interesting to other developers, here’s some of the stuff in my utility belt.

count(array) – for counting the number of items in an array. The default PHP count() function will return the number of characters if you pass it a string instead of an array. Someone probably thought that was useful, but what it means is that you have to test that what you’ve got is an array (with is_array()) before you count it, which is a pain. So my count() function checks that it’s got an array, and returns zero if it’s not.

debug(string, type) – writes a line to the output log. This is an essential part of my development flow. Instead of using echo, print or print_r to debug, I just throw everything through Util::debug() and it all outputs neatly at the end of the page. It’s just like Firebug’s console.log(). My database class outputs all SQL that is executed, and any errors generated, to the same place. If I pass in an array, it’s automatically print_r formatted. Queries are counted, execution is timed and it all spits out right at the end of the page in glorious technicolor. I wouldn’t be without it.

html(string) – encodes a string for safe HTML output. This essentially ends up calling htmlspecialchars() but does so in a controlled way, ensuring that the correct encoding and quote options are used. It’s also quicker to type.

redirect(url) – sends a Location header and stops page execution. This basically just uses the header() function as normal, but crucially also calls exit so I can’t forget. It also gives me a central point to hook into if I need to stop all redirects occurring when debugging.

setcookie() – sets a cookie. This just makes sure the dates are set in the correct format etc, and hooks into my standard site configuration system to make sure the cookie domain is right.

contains_bad_str(string) – checks for known spam-attempt strings in user email form submission. I pinched this from Rachel a while back – it checks the string for things like multipart/mixed that should never occur in user-entered text, but could indicate an attempt to send spam via your e.g. contact form.

is_valid_email(string) – checks the format of an email address. Still an impossibly fiddly task. I don’t use this as much as I used to, as some of the PHP 5.2 filter stuff contains email checking, which is probably better tested.

pad(int) – if the number is below 10, returns it as a string with a ‘0’ on the front. e.g. 9 becomes 09. There are lots of ways to do this (such as using str_pad()), but this little function handles 99% of my common cases when dealing with formatting dates etc.

send_email(to, from, subject, body) – sends an email. This is a wrapper around the mail() function, but checks to see if it should be BCCing the sysadmin and does that if necessary. It also handles all the weird mail header options in a nicer way.

ssl(url) – rewrites a URL to use, or not use, HTTPS. This should be named with a verb, but I think I went with this for brevity. My site config settings dictate when a site (or part of) should be using SSL, so this function checks that and rewrites the URL as necessary. Super useful when you’ve got a site that uses SSL live, but you don’t have a certificate configured on your local development system.

urlify(string) – makes a URL-friendly representation of a string. I use this constantly for URL slugs. It lowercases the string, strips out any non-ascii characters and replaces spaces with dashes. Basically it turns “Hello World!” into “hello-world”, ready for use in a URL.

generate_random_string(length) – generates a string of letters and numbers, to the length specified.

excerpt(string, words) – returns the number of whole words from the string that you specify. Useful for little boxouts and that sort of thing where you need to control the amount of text that is output.

since(date) – returns a string such as “1 minute ago”, “2 hours ago” by comparing the date given to the current date and time.

rss_date(date) – formats the date in the weird format that RSS feeds require. I used to get sick of looking this up and piecing it all together, so just made a reusable function out of it.

array_sort(array, column, desc) – sort a multi-dimensional array. I stole this from Tim Huegdon. Grab it yourself – it’s useful!

That’s a selection of some of the generic stuff I’ve got kicking around and use on a day to day basis. None of it is unique, clever or not 100% achievable in any number of ways in PHP, but that’s not the point. It’s about abstracting away enough of the minutia to help me be productive and concentrate on the bigger problems I’m trying to solve.

What’s in your utility belt?