Please visit my new campsite listing site ukcampingmap.co.uk


Archive for the ‘Web development’ Category

A greasy framework

Monday, December 14th, 2009

As I think I may have mentioned, the latest project I worked on I’ve been using the Zend Framework for all the server-side development. Over the last few months I’ve developed a love hate relationship with it. On the plus side it does pretty much everything I need without needing too much customisation, a few of the negatives though are:

  • The quickstart in the documentation assumes way too much background information about configuration of a php app and data sources etc. They don’t seem to have considered that a reason many programmers use zend is because they don’t know too much about back-end development and want something to take care of the tricky bits for them. It took ages to get past this stumbling block, with the help of this tutorial (WARNING: The bit on connecting to the database either uses quotes when it shouldn’t or vice versa) and this website with tutorials on various zend components.
  • Having said it does everything, there are lots of gaps. I’m sure a lot of thought goes into deciding what gets included and they must get all sorts of requests, but some simple standard things are missing, eg a validator to check a confirm password field. Nevertheless it is fairly easy to write extensions, but the zend documentation site should have a lot more and clearer information on this. Linked to this, there seems to have been very little thought put into building some sort of community to share plugins, unlike jQuery, for example.
  • You may have sensed that I don’t have a great deal of respect for the documentation. It’s very sloppy to be frank. There are so few cross-links to different sections, and a lot of the classes contain examples which I found fairly irrelevant, covering a way of doing things unlikely to be used in a real website (eg the examples for querying your database don’t really use the Model-View-Controller structure you’re supposed to use). And, in my view, it’s way too wordy, and much of the text is just waffley clutter; far more so than better examples of documentation, such as php and google maps. The website is also very difficult to navigate.

To fix the final gripe I’ve written a greasemonkey script (my first ever one) to replace the existing documentation layout with one a little easier to negotiate.

Before greasemonkey

Before greasemonkey

Before greasemonkey

After greasemonkey

Wide open space

Friday, December 11th, 2009
Not a LOL cat

Not a LOL cat

My laptop (now on its very last legs) has a fairly dinky screen. It’s wide enough to not be a problem, but the height is always a pain, especially that now (unlike when I bought the laptop all of 4 years ago) I am a web developer and routinely have firebug and the web developer toolbar open, which sucks up about two fifths of the height of my screen.

Enough is enough, and I’ve decided to get tough on undesirable widescreen, tough on the causes of undesirable widescreen.

First off, although I don’t like Google Chrome’s tabs at the top interface, I do like the fact that they’ve squeezed something useful onto the otherwise desolate windows title bar, i.e the bar at the top of the screen that tells you which program you’re using and, in firefox, the webpage’s title. As I have no need for firefox to tell me anywhere other than on the tab which web page I’m on, this bar is pretty much useless. And, luckily for me, there is a new firefox extension to get rid of it: Hide Caption. It shifts the close, maximise and minimise buttons down to near the search bar and gives me an extra cm of space. It warns that it may not be compatible with tab-mix plus, though I haven’t had any problems, and I use loads of other extensions too with no clash. Although I did uninstall another plug-in called Hide Navigation Bar as this didn’t work, but it may have been a clash.

A few of other things I’ve done to save space and decrease clutter is decrease the text size in firebug, change my windows taskbar to a single row rather than two, use the personal menu extension to hide the menu bar, and got rid of my bookmarks toolbar (although not sure how long that will last). It would be really handy if firebug could have an option to place it to the side of the screen rather than the bottom. Most of the time the lines don’t span the width of the console, so it’d be a great space saver to stack them vertically down a narrow strip at the side of the page.

Incidentally, one of the few add-ons that has remained a constant for me over the years is the qute theme. It’s really nicely designed with light colours and small icons and makes the screen seem a lot less cluttered. There’s two versions available at the moment; the authentic new version for firefox 3.5, and the retro version based on the original icon designs from years ago, which is the one I plump for. Aside from being aesthetically more pleasing it also has the advantage of not having a heart as the icon for bookmarks, which always took me a second to work out what it meant.

Anyway, here is my current, much cleaner looking, firefox appearance now (I would do a before and after, but it’s way too much hassle to go back and disable all the things I’ve changed):

Slimline firefox

Well I never

Thursday, December 10th, 2009
Colouring in

Colouring in

If there’s one thing I know when it comes to web development, it’s CSS. I don’t always write it in the most organised fashion (though I like to think I do when I’m given a finished design to work from), but for over a year now I’ve felt that my knowledge about the bits of CSS that I use daily is pretty complete*. And for the bits I don’t have to use very often I an always find what I need on the internet.

So imagine my surprise today when I realised that there’s one area of CSS that I use everyday with a fetaure I was completely unaware of. I’d always thought that

p{color:red}

meant “Make the text in the paragraph red”, but it turns out that that’s not the full story.

In all browsers, it seems, if border-width and border-style are defined for an element, but no border-color, then color also defines the border colour. But then if you define a value for border-color then color gets ignored when calculating the border colour. Even if you use another selector of higher specicifity to set a new value for color this still has no effect on the border colour. Here is a demo page.

But is it of any use?

Well, yes – it turns out it is.

Let’s say you want to define a generic button item as follows

.button {display:inline-block;border-width:2px;border-style:solid}

Then you can coordinate the text and border colour of the buttons by just using, eg

.cancel {color:red}

And this technique could be used for all sorts of generic elements where text colour and border colour are normally same. To use a different colour for the border it’s an easy thing to over-ride too.

Has anyone ever included both the British an d American spellings of colour this much in one article before?

* excluding newly emerging vendor-specific styles, eg -webkit-make-it-look-cool {}

Ternary gets a turn

Thursday, December 3rd, 2009

I’ve recently started using the ternary operator more. For those not in the know already, it’s a bit like shorthand for

if () {
} else {
}

but with a few similarities to other parts of the language too (NB this is based on the javascript implementation – other languages may differ slightly).

So, in the simplest case, instead of writing

if (statement)
{
   codeblock1
} else {
   codeblock2
}

we can write

(statement) ? codeblock1 : codeblock2 ;

which is a great way of cutting down on lines of code when each code block is only a single line. A few tricks to make using it more fulfilling are as follows.

The ternary operator can be split over two lines

So instead of

(statement) ? codeline1 : codeline2 ;

I mostly use

(statement) ? codeline1 :
              codeline2 ;

I find it more readable, as it really draws out the structure of what the code is doing. It also looks a bit like a switch statement (which, incidentally, I hear runs slow in javascript), which will come in useful later.

You can get rid of the brackets/parentheses

I tend to leave them in though as if the statement to be queried is long it would otherwise be easy to not notice that at the end of it comes a ?. The brackets remind you that what’s within is to be evaluated as true or false.

The ternary operator doesn’t have to start the line, and often shouldn’t

The following lines are equivalent:

(cetacean.mass > 1000) ? var family = 'whale' : var family = 'dolphin';
var family = (cetacean.mass > 1000) ? 'whale' : 'dolphin';

As you can see the second version results in less code, which is also easier to comprehend as the action of the line – assigning a value to a variable – is clear from the beginning of the line. As a rule of the thumb I put as little within the ternary operator as possible.

(As an aside the && and || operators – normally seen within if statements – can also be employed, using similar syntax, to assign values to variables. This is why I don’t think it’s fair to say that the ternary operator is just shorthand for if … else …, as it bears similarities to other bits of the language too. )

Sometimes the ternary operator can’t start the line

The only example I’ve come across so far is

return (cetacean.mass > 1000) ? 'whale' : 'dolphin';

Putting the return after the statement to be queried causes an error.

The ternary operator can be nested to emulate ‘else if’

First of all

if(statement1) {
  code1
} else if (statement2) {
  code2
} else if (statement3) {
  code3
} else {
  code4
}

Can be rewritten as

if(statement1) {
  code1
} else {
  if (statement2) {
    code2
  } else {
    if (statement3) {
      code3
    } else {
      code4
    }
  }
}

and so on for more statements.

But we know ifs can be rewritten using ternary, so it’s also equivalent to:

(statement1) ? code1: ((statement2) ?  code2 :( (statement3):?code3: code4));

which can unbelievably be rewritten on more lines as

(statement1) ? code1 :
(statement2) ? code2 :
(statement3):? code3 :
               code4 ;

So now you can construct very concise, relatively fast and, in my humble opinion, readable if … else …/switch statements. This is particularly valuable for defning  the value of a variable quickly, and based on a variety of conditions, eg:

var family = (cetacean.mass > 1000)             ? 'whale' :
             (cetacean.noseshape == 'cylinder') ? 'dolphin':
                                                  'porpoise';

Neat!

This literally changes

Monday, November 30th, 2009

You should know that I’ve built up a lot of half-written posts recently, mostly about javascript, so this blog, as it emerges from semi-hibernation, is gonna get code-ier and more out of date as I work backwards.

So to begin at the end, I recently came across a bug which is far from obvious to track down. Look at the code below.

var MyClass = function() {
  this.a = 'dolphin';
  this.getA = function() {
    return this.a;
  }
}

myObject = new MyClass();
var callbacks = {callback1: myObject.getA}
newA = callbacks.callback1();

What will the value of newA be?

In my application, in which I used callbacks to store the callback functions for a series of custom-made dialog boxes, I was expecting the value to be a, but it isn’t. The reason for this is that callbacks is an object, and saving a function as a property of an object is, in effect, creating a method of that object, and methods of objects, when called using the ‘.’ syntax, will tend to have this refer to the object (not always, but normally). So in creating the callbacks object you inadvertently cause getA to fail as this no longer points to the myObject object, but to the callbacks object literal.

Fair enough. But what makes this error particularly difficult to track down is that firebug shows console.log(callbacks) to be an empty object. Why this is, I don’t know – it seems unlikely to me that the properties wouldn’t be created due to the value of this being reassigned, so maybe it’s a mistake in firebug ( a firebug-bug, if you will). A similar error occurs when using an array as callbacks instead of an object, but firebug reports that the function is stored in the array, and that it returns an undefined value, so it’s a lot easier to see what the problem is. But once the bug is found, the workaround for the array and the object is the same.

The method I’ve chosen is to define

var that = this;

at the top of the MyClass function, and anytime you use this but think it may be called in such a way that the context may change, substitute that for this. But this is far from perfect – you have to second guess when you will need to do this as it’s not always obvious, and you could easily miss an instance which doesn’t occur very often, but which is fatal when it does. Another solution is to use the prototype.apply method to explicitly set the context of the method, though it looks ugly and a bit indecipherable. On the other hand it is a lot more bulletproof.

I’m sure you’ll make the right decision.

(More sponge creature fun here)

But it works for me!!!

Monday, November 16th, 2009

The lines of javascript below, included at the top of your scripts, could save you a lifetime of confusing conversations with clients where they say an application doesn’t work and you can clearly see that it works on your laptop.

The difference is that you have firebug installed and they don’t, so for you console is defined, but for them it is not, so if you leave any references to it in the app it will throw an error for them. But this fixes that;

if(!console) {
 var console = {};
 console.log = function() {
   return null;
 };
}

A useful debugging method

Friday, October 30th, 2009

I’m always dismayed by the lack of debugging information out there. Yes, there is plenty of information on how to fix particular bugs, but very little on the more general heuristic processes for finding the source of a bug. This may be because debugging is, by its very nature, a thankless process of trial and error.

But nevertheless, I’ve just discovered for myself (though it may be common practice for others already) a technique for debugging when the bug lies within a function which runs numerous times without fail, but when fired on another particular occasion, fails. For example, you have one function which creates shopping basket items from all your user’s saved data at startup, but when you try and use the same function later to create another item based on user input, the function fails.

Putting some var_dump() [php] or console.log() [javascript] calls inside the function will result in reams of information being printed out, most of it useless as its produced by the successfully running first calls to the function. So what I now do is this:

Change

function myFunction(param1, param2, ..., paramN) {
    some = code;
    console.log(something);
    some = more(code);
}

to

myFunction(param1, param2, ..., paramN, test) {
    var some = code;
    if(test) {
        console.log(something);
    }
     some = more(code);
}

And change the function call that needs debugging from

myFunction(a, b, ... N)

to

myFunction(a, b, ... N, true)

Now you will only be shown the debugging messages when you need them. It’s particularly useful for javascript as the console area of firebug is so small so its good to limit messages to only those which are relevant.

Clever stuff with tables

Monday, September 28th, 2009

I’ve recently been getting to grips with the zend framework. I’ve been meaning to blog about it for a while, for there is much to discuss: appalling introductory tutorial, a class reference which for some reason is nowhere near as easy to use as others… but I will touch on all that some other time.

But I thought I should post this up before I forget. The site I’m working on at present has three kinds of users: superusers, teachers and students, with a separate database table for each kind. The tables for each could have been slightly different but I decided to make them all the same (with dummy entries in the few irrelevant columns, though later I may discover I can discard these). The reason for keeping the structure uniform was that I had an inkling that if I did I could use just one model in Zend to access all three tables… and the inkling was correct.

It took a little debugging and investigation of the Zend_DB_Abstract class, so for the benefit of others, to have a model that works for a number of tables simply start your class defininition as follows:

class Model_DbTable_GenericName extends Zend_Db_Table_Abstract
{
   protected $_name = '';

   public function __construct($type,$config = array()) {
     parent::__construct($config = array());
     $this->_name = $type;
   }
   ⋮
}

And to instantiate a DB model use the following:

$Data = new Model_DbTable_GenericName('specifictablename');

Whether or not your tables have to have exactly the same structure depends on how you define all your functions for interacting with the data – you might need to use conditionals if some tables have more or less columns than others.

Html 5 will kill us all

Saturday, September 26th, 2009

Being a font-end web developer is looking very interesting/scary at the moment. The web is awash with talk of html 5, how we should all be taking advantage of it now, and the various tools by Google and others for making it possible despite what internet explorer fails to implement.

It is, quite literally, mental!*

The last year of my web life has seen me learn more stuff (php, javascript, jQuery, Google Maps, Zend framework and more), more quickly than ever before, and there’s still a load of things uncompleted on my to-do list, Flash being the most prominent hole in my arsenal…

…until now.

My firefox has about 20 tabs open, most of them containing information about my industry that wasn’t very relevant until a few weeks ago. Now, if I’m to keep touting myself as a front-end developer of any quality I will have to learn about:

  • Vector graphics and animation, which will mean getting to grips with Adobe Illustrator and some vector graphics oriented javascript libraries which make working with Scalable vector graphics and the canvas element easier
  • The not inconsequential lengthening of the list of tags available for use in markup
  • Consider using  lot more javascript libraries as my approach to getting websites to work in ie, which runs contrary to what I’ve always done before.
  • And many more things, essentially revolving around the fact that so many things that designers would always have liked to do on websites have suddenly become feasible.

On the bright side though, SVG and canvas combined with some other subtler features of html 5 could make Flash relatively obsolete, which increases the value of the time I’ve spent learning javascript. The project I’m about to start working on was initially conceived as a Flash game, but as there’s very little animation involved I was able to propose writing it as a javascript game instead. With html 5′s new features there will be very little to elevate Flash above javascript any more in any context. Html 5 can even natively embed video.

Everything’s going to be alright.**

*I’ve been watching peep show this morning and feel constant urges to write a bit like Super Hans or Jeremy.

** or Mark

Saving my neck

Wednesday, September 23rd, 2009

I don’t want to end up like the giraffe in the picture: a crick-necked invalid with blotchy skin. As I grow older the blotchy skin is probably inevitable, but the crooked neck/back is avoidable I hope.

The trouble is that for a living I do a mixture of two things:

  1. Bent double over a laptop, twisting my fingers at unreasonable angles in order to reach a keyboard shortcut
  2. Bent double over a guitar, twisting my fingers at unreasonable angles in order to reach a wicked chord

Both these activities lead to my back muscles being tensed in an uncomfortable position, with little movement to get blood flowing to the muscles. As an added bonus, my finger muscles are also generally making the same kind of not particularly relaxed movements every day.

So what’s the antidote to all this physical self-abuse?

The idea I’m trying at the moment is juggling.

I’ve been able to juggle for a little over a year, and several of my friends are fanatical about it (working for little while in a backpackers hostel in Amsterdam is a surefire way to get people to help/force you to pick up the basics), but I hadn’t done very much since the first months when I first picked it up.

Recently, however, I realised that juggling is the antithesis of the activities that are determined to wreck my spine:

  • Rather than crouching forward, to juggle you really need to stand quite upright; if you lean forward you end up throwing the balls forward, which eventually leads to either dropping them or running after them into traffic or something.
  • More related to guitar playing this, but juggling requires very relaxed, fluid movements of the arms and shoulders. While fluidity is essential to playing rhythm guitar well, it’s impossible to avoid tensing up somewhat during the pacy irish reels we play – there simply isn’t enough time between beats to led your arm lollop along. So juggling should hopefully help counteract the stiffness I’ve been getting in my upper back.
  • Despite the fact that you’re constantly grasping in the air to catch a ball, juggling requires you to relax your hand muscles too. Catching a ball when you juggle isn’t about holding it tightly; if anything, it’s closer to forming a cup shape for the ball to nestle into.

So, that’s the summary of why I think juggling might help. I’ll keep you posted on whether or not it is the miracle cure I’ve been looking for.