Why <img> shouldn’t be a self-closed tag

Posted on May 16th, 2012

The HTML <img> tag is self-closing, meaning that you write it likes this

<img src=”lolinternet.jpg” alt=”lol” />

and not like this

<img src=”lolinternet.jpg” alt=”lol”></img>

The <canvas> tag isn’t self-closing and that is very useful because the content of the element is the fall-back that the browser shows if it doesn’t support <canvas>, like so

<canvas id="myDrawing" width="200" height="200">
<p>Your browser doesn't support canvas.</p>
</canvas>

If your browser doesn’t support the <canvas> then it shows the <p> element instead. That’s cool but all browser’s support <img>, right? Yeah, they do, but not all images specified are available to download and so it’d be great to have a fall-back specified in the HTML if the image wasn’t found. I could imagine this being useful in e-commerce systems that show product images and want to show a “no image available” image if the product doesn’t have it’s own. You could do

<img src=”nicebike.jpg” alt=”a nice bike”><img src=”noproductimage.jpg” alt=”"></img></img>

Providing a fall-back image is easy enough to do with either JavaScript or your server-side language but it would be neater to let HTML deal with it.

Photo by: Todd Barnard

Using native PHP sessions with CodeIgniter

Posted on May 9th, 2012


This post explains how to use native PHP sessions ( the $_SESSION[''] global array ) with CodeIgniter 2.1.0 in place of CodeIgniter’s default session storage. 

CodeIgniter doesn’t use standard PHP sessions, instead it saves session-data directly in a browser cookie, which limits the amount of data you can save to 4k. Even though it is good practice not to store a lot of data in session it’s unlikely that 4k is going to be enough for any reasonably complicated website. I find it kinda odd that the CI developers didn’t at least give us a configuration option to switch to using standard PHP sessions. Luckily for us it is easy to add a library to save the day.

Creating the Nativesession library

A CodeIgniter library is simply a class that is loaded by the framework and made available for you to use in your Controller classes. It’s simple but a really nice way to include your own code without having to add include statements and instantiation code into each controller that you create. We are going to create a new library that starts a native PHP session and allows us to store and retrieve things from it:

Create the native session class

Inside your CodeIgniter project you have an application/libraries folder, create a new file called Nativesession.php in there. Put the following code into Nativesession.php:

if ( ! defined('BASEPATH') )
    exit( 'No direct script access allowed' );

class Nativesession
{
    public function __construct()
    {
        session_start();
    }

    public function set( $key, $value )
    {
        $_SESSION[$key] = $value;
    }

    public function get( $key )
    {
        return isset( $_SESSION[$key] ) ? $_SESSION[$key] : null;
    }

    public function regenerateId( $delOld = false )
    {
        session_regenerate_id( $delOld );
    }

    public function delete( $key )
    {
        unset( $_SESSION[$key] );
    }
}

If you’ve used PHP sessions before then that code should be pretty self-explanatory, if not, check the PHP site for more info.

Using your new library in a controller

You use your new library in the same way as you do any other CI library:

class Login extends CI_Controller 
{
    public function index()
    {
        //load our Nativesession library
        $this->load->library( 'nativesession' );		

        //Read the username from session
        $username = $this->nativesession->get( 'username' );

        //Update shopping cart session data
        $this->nativesession->set( 'cart', $cart );
    }
}

You can now use your new Nativesession library in place of the CI-supplied session library.

Photo by: rafeejewell

PHP 5.4 syntax changes to make your pants tingle

Posted on April 16th, 2012

It’s the little irks and annoyances in a programming language that makes you love it or hate it. A language that has a terse syntax and plenty of quick ways to accomplish common programming tasks will win a developer over. PHP 5.4 has just been released and has a few changes in it that might be considered insignificant by some, but to a programmer who likes to write less code in less time, who likes to get stuff done, they are awesome additions.

Class member access on instantiation

I’ve already written about this one. As of 5.4 you can call a class member on instantiation, so if you are instantiating a class only because you need to call one of its functions or access a single member once, you can do it in one line of code. Instead of:

$s = new Bingo();

$s->house();

you can write:

new Bingo()->house();

Shorthand array syntax

Saving some more typing and making your code a bit more readable, the array creation syntax uses [] as well as array().

$s = [1,2,3,4];

$t = ['one' => 1, 'two' => 2, 'three' => 3, 'four' => 4];

 

Creating a JavaScript templating function

Posted on January 12th, 2012

Templating provides a separation of concerns between your data and its display. Back-end languages like Java and PHP have been using templating as part of the MVC paradigm for years and as JavaScript gets used to create bigger, better, more complicated client-side apps the need for clean code become more important.

There’s already a number of MVC frameworks and templating libraries for JavaScript, Backbone and Mustache are good examples, but I decided to re-invent the wheel just so I could see how the wheel worked.

My wheel will parse a template and replace any elements in the format {{property_name}} with an object property called property_name. For example, this code:

var data = {fstname: 'steve', surname: 'claridge'};
tmpl( "Hello {{fstname}} {{surname}}", data );

Will find {{fstname}} and replace it with data.fstname and find {{surname}} and replace it with data.surname. The resulting string being Hello steve claridge.

Here’s the tmpl() function:

var tmpl = function(tm, data) {
    var s = tm instanceof Element ? tm.innerHTML : typeof jQuery == 'function' &&
            tm instanceof jQuery ? tm.text() : tm;

    return data == null ? s : s.replace( /{{(.*?)}}/g, function(s, p1) {
        return typeof data[p1] === 'function' ? data[p1]() : data[p1] || "";
    });
};

The function has two parameters: tm is the template and data is the object containing the data to insert into the template. tm can be a string, a jQuery object or DOM Element.

Some more examples, which show the different template parameter types:

<script id="t1" type="text/html"><p>{{name}} {{surname}} scored {{total}} points</p></script>

<script>
var d = {name: 'steve', total: function() { return 16 * 4; }, surname: "claridge" };

tmpl( document.getElementById('t1'), d )
tmpl( document.getElementById('t1').innerHTML, d )
tmpl( $('#t1'), d )
tmpl( $('#t1').text() );
tmpl( "<p>{{name}} {{surname}} scored {{total}} points</p>", d )
</script>

Storing the templates

John Resig suggested an excellent way of storing the templates in the HTML document such that they are not displayed as part of the <body> and are not scraped by search engines. Use the <script> tag with type=”text/html” and any HTML can be stored as a template and because of the text/html type will not be executed as JavaScript. It parses as valid HTML as well.

GAME shares slump after disastrous Christmas

Posted on January 12th, 2012

GAME, the video game retailer, saw shares slump by 40% after like-for-like sales tumbled 15.2% in the eight weeks to 7 January. This isn’t particularly surprising as most big-grand stores are reporting a downturn on sales and profit over the Christmas period.

It is very difficult to see any kind of future for bricks-and-mortar stores that sell products that can be purchased online through established e-retailers. Products like games, CDs, DVDs and books can always be purchased for less on the web. If the bricks-and-mortar store doesn’t offer anything more than being able to walk in and buy the product then what future do they have?

Some years ago you could play a game-console in-store to try out new games and often that was the only way to try before you buy, but these days all major console platforms have demo versions of new games downloadable for you to test the water with.

The only reason to buy a game, CD, DVD or book from a brick-and-mortar store these days is if you need it immediately and can’t wait the 2-3 days for delivery.

What’s more the inflated high-street prices for these products can no longer be disguised as good value; more and more consumers are using their smartphones to compare prices with online alternatives whilst in-store.

These stores are doomed, it’s only a matter of time.

Creating JavaScript string startsWith() and endsWith() functions

Posted on December 30th, 2011

JavaScript strings don’t have native startsWith() or endsWith() functions. Fortunately it is very easy to add them to the string prototype so that you can use them throughout your code. Here’s some code for the two functions:

if ( typeof String.prototype.startsWith != 'function' ) {
  String.prototype.startsWith = function( str ) {
    return this.substring( 0, str.length ) === str;
  }
};

alert( "hello world".startsWith( "hello" ) );

if ( typeof String.prototype.endsWith != 'function' ) {
  String.prototype.endsWith = function( str ) {
    return this.substring( this.length - str.length, this.length ) === str;
  }
};

alert( "hello world".endsWith( "world" ) );

It is worth noting that the functions above will return true if “” is passed as the string to compare, these will return true

"hello world".startsWith( "" );
"hello world".endsWith( "" );

If you don’t want this to happen then add a length check to the two functions, so they now look like this:

if ( typeof String.prototype.startsWith != 'function' ) {
  String.prototype.startsWith = function( str ) {
    return str.length > 0 && this.substring( 0, str.length ) === str;
  }
};

if ( typeof String.prototype.endsWith != 'function' ) {
  String.prototype.endsWith = function( str ) {
    return str.length > 0 && this.substring( this.length - str.length, this.length ) === str;
  }
};

In the code above I’m using substring() to check if a string starts or ends with the parameter, this is quicker than using indexOf() as that has to scan the whole string to find a match and that can be slow for long strings.

Adding far-future expiry times for static content in a Java application

Posted on December 22nd, 2011

Having to serve lots of static content is a common factor in poorly performing websites. It is not unusual these days to have to download 50+ images, 10+ JavaScript files and several CSS files to properly display a webpage. Even when a server can deliver a static file in less than a second the number of files that need to be downloaded to render a page soon push the page-load time to be unacceptable.

There are a number of ways to unburden your server from having to continuously serve static content, some easy and some less so. This post is about setting an Expiry Time on your static files so that browsers know that they do not need to keep re-downloading the same  file all the time. This is especially useful if you have lots of repeat visits from the same browser.

An HTTP header is sent to the browser with all downloaded files. This tells the browser the size and type of the download, among other things, and can also be used to tell the browser the lifetime of the downloaded file; in other words: the length of time after which the browser should fetch a fresh version of the file from the server.

By default most browsers will re-fetch all files that are needed to render a webpage on each new session, where a session is a newly opened browser instance, new window or new tab. You can alter this behaviour and tell the browser to re-fetch after a period of time, to do this you set one or both of the following HTTP headers:

Cache-Control: Tells all caching mechanisms from server to client whether they may cache this object. It is measured in seconds

Expires: Gives the date/time after which the response is considered stale

An example of these headers in an HTTP response:

Cache-Control: max-age=3600

Expires: Sun, 01 Dec 2013 16:00:00 GMT

The Expires header was introduced in the HTTP 1.0 spec and Cache-Control in 1.1. All modern browsers should support both headers but to be on the safe side you can send both.

A simple way to send these headers for static content in your Java app is to use a Filter. There’s two pieces to this: some XML to add to your web.xml file and a Java class. To understand how filters work, read this.

    <filter>
        <description>Set cache expiry for static content</description>
        <filter-name>ExpiresFilter</filter-name>
        <filter-class>moreofless.ExpiresFilter</filter-class>
        <init-param>
            <description>Add an Expires Header</description>
            <param-name>days</param-name>
            <param-value>30</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>ExpiresFilter</filter-name>
        <url-pattern>*.css</url-pattern>
        <dispatcher>REQUEST</dispatcher>
    </filter-mapping>
    <filter-mapping>
        <filter-name>ExpiresFilter</filter-name>
        <url-pattern>*.jpg</url-pattern>
        <dispatcher>REQUEST</dispatcher>
    </filter-mapping>

The web.xml snippet above creates a new Filter called ExpiresFilter, which has one parameter called days – change days to be the cache expiry time for the static files defined in the filter-mapping section(s). For the sake of brevity I have only shown filter-mappings for *.jpg and *.css but you can of course add all your static file-types by adding new filter-mapping elements.

package moreofless.filter;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

public class ExpiresFilter implements Filter
{
    private Integer days = -1;

    @Override
    public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain )
                          throws IOException, ServletException
    {
        if ( days > -1 )
        {
            Calendar c = Calendar.getInstance();
            c.setTime( new Date() );
            c.add( Calendar.DATE, days );

            //HTTP header date format: Thu, 01 Dec 1994 16:00:00 GMT
            String o = new SimpleDateFormat("EEE, d MMM yyyy hh:mm:ss zzz").format( c.getTime() );            
            ((HttpServletResponse) response).setHeader( "Expires", o );
        }

        chain.doFilter(request, response);
    }

    @Override
    public void init( FilterConfig filterConfig )
    {        
        String expiresAfter = filterConfig.getInitParameter("days");
        if ( expiresAfter != null )
        {
            try
            {
                days = Integer.parseInt( expiresAfter );
            }
            catch ( NumberFormatException nfe )
            {
                //badly configured
            }                       
        }
    }

    @Override
    public void destroy()
    {
    }
}

This is a very standard Filter implementation. The init() method reads in the days parameter from web.xml and throws and exception if it is not a valid integer. The doFilter() method adds the days specified to the current date and outputs the HTTP header, note that the Expires header has the specific date format shown. I haven’t set the Cache-Control header in the code above but you can easily modify the doFilter() method to do so, remember that that header is specified in seconds.

PicStrips – a jquery plugin to give your images a little something

Posted on December 11th, 2011

PicStrips is a little jQuery plugin that I created after seeing a nice magazine layout by Teresa Wozniak. Basically, the plugin lets you split any image on your webpage into a number of vertical strips, where each strips has a horizontal gutter – alternate strips also have top/bottom vertical gutters. It kinda gives an image a bit of life, makes it stand out a bit and grabs people’s attention.

In the future I’d like to add some randomness to the size of the vertical gutters. I might convert it into a WordPress plugin if there’s any interest in that.

Check out the PicStrips page for more info, code examples and downloads.

Allow method chaining for fluent APIs

Posted on December 5th, 2011

Method chaining means being able to call multiple methods of an object whilst not having to respecify the owning object on each call. Assume we have an object with three methods, one(), two() and three() – assuming you wanted to call all three methods you would normally do this:

MyObject m = new MyObject();
m.one();
m.two();
m.three();

With method chaining it would look like this:

MyObject m = new MyObject().one().two().three();

Kinda neat! This technique is used a lot in Javascript and it’s seen throughout jQuery. Method-chaining creates easy to use APIs and shorter, cleaner code. To implement this in your objects is actually very easy, all you need to do is to return the Object from your setter methods. For example, a simple Java class with some setters:

class Stuff
{
  private String _one;
  private String _two; 

  public void setOne( String o )
  {
    _one = o;
  }
  public void setTwo( String t )
  {
    _two = t;
  }
}

Stuff s = new Stuff();
s.setOne( "one" );
s.setTwo( "two" );

It’s pretty standard to return void from setter methods. But if you change them to return Stuff then you can chain the setters.

class Stuff
{
  private String _one;
  private String _two; 

  public Stuff one( String o )
  {
    _one = o;
    return this;
  }
  public Stuff two( String t )
  {
    _two = t;
    return this;
  }
}

Stuff s = new Stuff().one( "one" ).two( "two" );

 

Photo by: marc falardeau