Widgets in PHP – Eliminating Copy and Pasting

Recently I have been doing a lot of work on tidying up the front-end of our PHP app. One thing that struck me is the amount of re-use of code for various widgets – and not the good sort.

Our example – A customer quote

Throughout our app it is common to see copying and pasting being used to acheive certain looks and effects. As an example, if we want to display a quote from one of our customers we could use something like:

<div class="Quote">
  <div class='StartQuote'></div>
    Awesome. Simply awesome.
  <div class='EndQuote'></div>

With the appropriate styles this creates something looking like:

sample quotes image

I know that this trivial example can be done entirely in CSS – but we all encounter things that can’t be done entirely in CSS and cross-browser compatible.

What’s wrong with this?

You may now be asking yourself this question. We want our quotes to all look the same so we get it right once then being copying and pasting – what is wrong with that? Well:

  • If we want the look to change we’ve got to change it everywhere
  • We’re prone to making mistakes when copying and pasting
  • It’s quite a lot of effort and mess for something that should be simple

An Alternative – Widgets

What we really want to do is: say what we want at a higher level, e.g.

    Awesome. Simply awesome.

Then have this snippet be replaced with the correct HTML. I call this a ‘widget’ based approach – we now have quote widgets everywhere instead of chunks of HTML.

Nice goal – how do we get there?

One word (ish): post-processing. PHP has a little known set of functions called ob_start and ob_end_flush. These can be used to send all your output to a callback function:

// Lots of HTML / Widget code

The post_process function takes a single string argument, the contents of the page, and returns a string, the post processed content – the content with the widgets replaced by the correct HTML.

Thoughts for the Future

I like this approach. I like being able to write my pages at the level that I’m thinking: quote here, panel there, calendar here… however, there isn’t yet a system that makes writing these new widgets easy – yet. Watch this space 🙂


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: