All in the <head>

– Ponderings & code by Drew McLellan –

– Live from The Internets since 2003 –

About

What's In Your Utility Belt?

15 October 2009

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?

- Drew McLellan

Comments

  1. § Morgan Roderick:

    I think I’ve rewritten my little FailFast library 4-5 times already.

    Once in Ruby
    Once in C#
    Two or three times in JavaScript

    One of these days, I think I’ll just do a complete rewrite in both JavaScript and Ruby, with plenty of tests and documentation and release it as open source for all to enjoy and improve upon.

    http://en.wikipedia.org/wiki/Fail-fast
    http://martinfowler.com/ieeeSoftware/failFast.pdf
    http://c2.com/cgi/wiki?FailFast

    When used intelligently, it provides valuable feedback and removes a lot of hairy debugging.

  2. § Thomas J Bradley:

    Your debug() method is really an interesting idea. I would love to see your code for doing that.
    I have a function pre(mixed) which calls print_r() then exits, which is often helpful for debugging, but your method seems really interesting.

    Another one I have found use for once and a while is arrayFlatten(array) that takes a multi-dimensional array and flattens it into a single dimension.

  3. § TheFella:

    I use PHP as well. I use one function to change a string into xhtml. I use this for headings from the db and suchlike.

    I also use one class that has a bunch of api functions in the class, so I can display x number of tweets/songs/links/photos/etc.

    social::lastfm(username)
    social::twitter(username)
    social::flickr(username)

    and so on.

    I also have a class that reads the last accessed time on a file, then adds that in as a folder name. So, /css/style.css becomes /css/1241576503/style.css and then I just use mod_rewrite to direct this back to the actual file. It allows me to bypass the browser cache every time I update a file. I prefer this method to /css/style.css?v=3.2.1

  4. § David Horn:

    Thanks for sharing … it’s a great way of working. I’m primarily a front-end designer but more and more am getting into development work – something like this comes into play, I guess, when you’re sufficiently up the learning curve.

    Thanks again,

    David

  5. § Ölbaum:

    So you’re teasing us with all your smart utility functions, but you’re not even selling your Util class? That’s mean. :-D

  6. § Dave Sparks:

    I have a few that get carried from project to project.
    Amongst various database query and XML parsing ones I have a debug, valid email, a variety of form functions (checking for BCCs etc) and a selected class function which gets added to menu items and tells if the current page is the same as the menu option and gives it a class selected.

    There’s certainly a few more I might put in from that list of yours Drew.

  7. § John Rainsford:

    I have a lot of functions for creating forms within my own CMS system, but I also have something similar to is_valid_email function and I also have a function for creating URL-safe titles (a regex that replaces spaces with underscores and only allows letters and numbers) for creating nice URLs. I keep them in a separate file and it really makes it easy to implement changes throughout a site or sites.

  8. § Matthew Spence:

    pre_dump is my must have debuggin util
    its basically a wrapper for var_dump but wraps it in pre tags

  9. § Phil Thompson:

    I use this function – which I borrowed from another developer:

    function read($array, $key, $default = NULL) { if(!isset($array[$key])){ return $default; } return $array[$key];
    }

    and can be used like so:
    $value = read($_POST, ‘email’);
    or
    $value = read($_POST, ‘email’, ‘default@email.com’);

    it just helps to prevent any applicable PHP warnings of array keys not existing

  10. § AttackMonkey:

    I have a utility assembly that gets ported from .net project to project, it’s split into different types of utility:

    - strings (password functions, strip html etc) – security (encryption functions to make it easier to change if need be) – datetime (handy date and time functions missing from c#) – errors (handling errors and emailing me detailed error information) – general (anything not in the above)

    Its evolved over time, but it’s a pretty hand thing to have!

Textile Help

Photographs

Work With Me

edgeofmyseat.com logo

At edgeofmyseat.com we build custom content management systems, ecommerce solutions and develop web apps.

Recent Links

Affiliation

  • Web Standards Project
  • Britpack
  • 24 ways

About Drew McLellan

Photo of Drew McLellan

Drew McLellan (@drewm) has been hacking on the web since around 1996 following an unfortunate incident with a margarine tub. Since then he’s spread himself between both front- and back-end development projects, and now is Director and Senior Web Developer at edgeofmyseat.com in Maidenhead, UK (GEO: 51.5217, -0.7177). Prior to this, Drew was a Web Developer for Yahoo!, and before that primarily worked as a technical lead within design and branding agencies for clients such as Nissan, Goodyear Dunlop, Siemens/Bosch, Cadburys, ICI Dulux and Virgin.net. Somewhere along the way, Drew managed to get himself embroiled with Dreamweaver and was made an early Macromedia Evangelist for that product. This lead to book deals, public appearances, fame, glory, and his eventual downfall.

Picking himself up again, Drew is now a strong advocate for best practises, and stood as Group Lead for The Web Standards Project 2006-08. He has had articles published by A List Apart, Adobe, and O’Reilly Media’s XML.com, mostly due to mistaken identity. Drew is a proponent of the lower-case semantic web, and is currently expending energies in the direction of the microformats movement, with particular interests in making parsers an off-the-shelf commodity and developing simple UI conventions. He writes here at all in the head and, with a little help from his friends, at 24 ways.