Archive for the ‘Programming’ Category

Modernizing Legacy Applications In PHP

Tuesday, December 8th, 2015 | Books, Programming

Modernizing Legacy Applications In PHP is a book by Paul M. Jones on how to bring legacy codebases up to date. Jones is a relatively big-whig in the PHP community, being involved in most of the PSR standards and a contributor to the Zend Framework.

For me, the book was both excellent and uninformative. What I mean by that is that I do not think I learnt anything from reading it. However, I flatter myself that I am pretty good at PHP and have spent many years working with legacy codebases. It was always been an interest of mine, and I have previously submitted conference papers on the subject. I have been doing just what this book describes with my current client.

That in itself shows the quality of the book though. It describes every step I have been going through in a logical and clear order. It explains introducing autoloading, separating out the concerns, adding unit testing and injecting your dependencies. It says you from the tangled mess to a clean and modern application in an easy-to-follow manner. In short, it is pretty much everything I would recommend to someone starting to clean up a legacy application.

It has code examples and some tips and tricks in it, but for the most part it is quite high level. It also deals with PHP 5.0 and onwards. There is perhaps room to expand here. At Buzz I had to come up with techniques to support ancient problems like register globals, and at the NHS I ran into PHP 4.6 installed on their servers. Solving these kind of problems, and the little code tricks you can do, might have been a useful additional also.

Overall, I would recommend this book to anyone who feels the least bit daunted by the idea of modernising a legacy PHP codebase. It is clear, easy-to-follow and takes you through exactly the steps you should follow.

modernizing-legacy-applications-in-php

SHOUTCLOUD WORDPRESS PLUGIN

Wednesday, July 1st, 2015 | Programming

HAVE YOU EVER WANTED TO CONVERT ALL YOUR BLOG CONTENT TO UPPERCASE? IF SO, I HAVE THE PLUGIN FOR YOU! I HAVE PUBLISHED A SHOUTCLOUD WORDPRESS PLUGIN THAT AUTOMATICALLY INTEGERGRATES YOUR BLOG WITH SHOUTCLOUD.

ADVANTAGES

  • AUTOMATICALLY CONVERTS ALL OF YOUR TITLES, CONTENT AND TAGS TO UPPERCASE
  • ZERO CONFIGURATION
  • ALL STRING MANIPULATION IS DONE IN THE CLOUD
  • INCREASES ANTIPCIPATION BY DRASTICALLY INCREASING LOAD TIME

DISADVANTAGES

  • NONE, EVERYTHING IS BETTER WHEN IT IS DONE IN THE CLOUD!

screenshot-1

Xenu’s Link Sleuth

Tuesday, June 23rd, 2015 | Programming

It is super easy to miss broken links on your website. Even if you test it rigorously, it can be difficult to catch them all. That is where an automated crawler can come in useful. Xenu’s Link Sleuth is one such tool.

It only runs on Windows, so I had to run it in a VM. It is also rather a blunt instrument – it crawls everything even though you can be pretty certain that if you have checked one article ID page, they are all going to work. But those few points aside, it is very useful.

It rapidly spiders all of your pages and reports back on both broken links and redirects. It checks CSS, JavaScript and images resources too, and you have the option to check external URLs as well so you get full coverage. It then spits out a HTML report. It is amazing how many little links you find that need fixing when you run it. Well worth spending a bit of time on.

Autop

Monday, June 22nd, 2015 | Programming

PHP has a function called nl2br that converts line breaks into <br> tags. This is really useful if you have content in a database and want to ensure the line breaks are in encoded in HTML without actually having to specify them in the content.

It is a bit of a clumsy tool though. It does not take into account that you might want to use paragraphs, or that you do not want br tags adding inside block elements such as pre or hidden elements such as script and style.

The programmers over at WordPress have done a great job of coming up with their own version that resolves all of these issues and many of us already benefit from it on our sites. Matt Mullenweg has written about it.

However, it is buried in the WordPress codebase, so if you want to use it in a non-Wordpress project, you have to mess about pulling it out of the codebase and inserting it into your own. To save myself from having to do this, I’ve created a project on Github that moves it to a standalone library. You can then drop this into your project using Composer and use away.

Speeding up Leeds Restaurant Guide

Friday, June 12th, 2015 | Limited, Programming, Tech

restaurant-guide-website

Leeds Restaurant Guide is incredibly detailed covering so many restaurants with high quality content and imagery. So it seemed only fitting that I should pay as much attention to the presentation as I do the content.

I’ve been using Google’s PageSpeed Insights tool to debug it. Ironically, PageSpeed Insights spends a lot of time complaining about the Google AdSense code that they provide to me. It does however provide some useful tips too.

Compression

Gzip compression costs almost nothing and can drastically reduce the file size you are sending to the client. The server compresses it and the client uncompresses it all of which is done transparently to the user.

It is pretty easy to configure using Apache’s mod_deflate module, and I’ve blogged about how to get it working on cPanel on Hardware Tutorials.

Expiry headers

If you have Apache’s mod_expires, and you almost certainly do, you can set default expiry headers for content using your .htaccess file.

<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType text/css "access plus 60 minutes"
    ExpiresByType image/jpeg "access plus 1 day"
    ExpiresByType image/jpg "access plus 1 month"
    ExpiresByType image/png "access plus 3 months"
</IfModule>

This will tell the client it can safely cache the content for a while. Put whatever values in that you think are sensible.

Minify your CSS

Recently I wrote about how to use Gulp to set up a task to compile your SASS/LESS stylesheets. This included instructions on how to minify your CSS. Even if you are just using plain old CSS, you could still create a task to create a minified version.

Minification takes out all the spaces, comments and other unrequired characters so that you have less data that needs to be transferred to the client.

Using Gulp to compile stylesheets

Thursday, June 11th, 2015 | Limited, Programming, Tech

gulp

If you’re doing a lot of CSS in your web development, you may have taken to using SASS or LESS to allow you to better organise, code and maintain your stylesheets. These are both great tools. However, the one thing that annoys me is having to remember the command to compile them, given it is often different for each project.

Luckily Gulp, a Node-based task runner, can come to the rescue.

This has the added advantage that you can also pipe it through other tools, allowing you to create maps and minify the CSS all in one command that makes it super easy.

Firstly, you need to add the dependencies so that NPM knows what to install.

{
    "devDependencies" : {
        "gulp" : "*",
        "gulp-sass" : "*",
        "gulp-minify-css" : "*",
        "gulp-sourcemaps" : "*"
    }
}

You can then run NPM install to get all the modules you need. If these are the only modules you are using you will probably need to modify your .gitignore file to ignore the node modules directory.

node_modules/

Now we can create a gulpfile.js in the root of our project directory that will define the tasks we want to run.

'use strict';
 
var gulp       = require('gulp');
var sass       = require('gulp-sass');
var minifyCss  = require('gulp-minify-css');
var sourcemaps = require('gulp-sourcemaps');
 
gulp.task('sass', function () {
    gulp.src('./sass-files/*.scss')
        .pipe(sourcemaps.init())
        .pipe(sass().on('error', sass.logError))
        .pipe(minifyCss({compatibility: 'ie8'}))
        .pipe(sourcemaps.write('./sass-maps'))
        .pipe(gulp.dest('./stylesheets'));
});
 
gulp.task('sass:watch', function () {
    gulp.watch('./style/*.scss', ['sass']);
});

The first task creates a “gulp sass” command that takes the SASS file, converts it to CSS, minifies it, builds the source map and then writes it out. I’ve set the compatibility to ie8, though it could also be ie7, and defaults to ie9.

The second task creates a “gulp sass:watch” which watches the files for changes and then calls the first task whenever it detects a change.

If you are using LESS you will need a slightly different set of dependencies.

{
    "devDependencies" : {
        "gulp" : "*",
        "gulp-less" : "*"
    }
}

The tasks are slightly different too, but basically do the same thing.

'use strict';
 
var gulp = require('gulp');
var less = require('gulp-less');

gulp.task('less', function () {
  return gulp.src('./app/resources/less/*.less')
    .pipe(less())
    .pipe(gulp.dest('./app/webroot/css'));
});

gulp.task('less:watch', function () {
    gulp.watch('./app/resources/less/*.less', ['less']);
});

The end result of this is that rather than remembering what the specific paths for any project I want to work on, I can create a Gulp task and simply run “gulp sass” or “gulp less”. I could even just rename them to “gulp css” to use the same name on every project I work on.

Tools for validating your website

Wednesday, May 27th, 2015 | Programming, Tech

There are some great online tools for validating that your website is looking and working well. Of course there are loads of these and many of them we’ve been using for years. Below though, I’ve listed a few I’ve been using the most in recent times or that are often overlooked.

W3C validator

An oldie but a goodie. The W3C validator ensures that your mark-up is valid. This is good for two reasons. One, it will find any problems, missing closing, tags, etc, that may be causing weird problems. Two, it will also point out stuff that you could be doing better like semantic tags and relevant meta tags.

http://validator.w3.org/

w3c-validator

Mobile friendly checker

Google are starting to crack down on websites that do not consider mobile users. Of course we all know we should be building mobile friendly websites, indeed, it should be mobile first these days! But it is hard to debug sometimes, especially given the fragmentation of devices.

Luckily Google now provides a tool that will give you a pass and fail, as well as showing you a preview of the site on an Android device. It’s not perfect, sometimes it fails to load assets and you have to come back later, but it is still an awesome tool.

https://www.google.co.uk/webmasters/tools/mobile-friendly/

Google Developers testing tool

Over on the Leeds Restaurant Guide we expose our reviews using the hreview schema. This means that sites like Google can see what ratings we give restaurants and put them direct in the search results. To check it is working correctly, you can use Google’s testing tool.

https://developers.google.com/structured-data/testing-tool/

Facebook Debugger

Recently I wrote about the Open Graph protocol which allows you to tell social networks (mostly Facebook) what titles, images and descriptions you want it to use when sharing a web page.

Facebook have a debugging tool to test your tags are working.

https://developers.facebook.com/tools/debug/

Making use of the Open Graph Protocol

Monday, April 6th, 2015 | Programming

When you paste a link into Facebook or other social networks (which in theory you could use) it generates a preview of the website including a title, image and description.

Webmasters actually have the power to suggest content for these items. This is something I recently implemented on the Leeds Restaurant Guide.

For example, the page is structured with the site name in the title and various images on the pages. However, when you post it into Facebook, it is pretty obvious to a human what information you actually want in there. You want the name of the restaurant and the image of the restaurant itself.

To suggest to the client what information I think would be best in there, I added some meta tags based on the Open Graph Protocol. For example, here is an example from Bibis.

<meta property="og:type" content="article" />
<meta property="og:article:author" conent="Leeds Restaurant Guide" />
<meta property="og:title" content="Bibis Italianissimo review" />
<meta property="og:image" content="http://www.leedsrestaurantguide.com/images/restaurants/Bibis%20Italianissimo.jpg" />

This provides helpful information to the client, usually Facebook, as to what information it should display where, making your site more sharable. Sites like BuzzFeed are all other these sorts of tags – just view their source code to see. This is why they are always so well presented and perhaps one of the reasons why they are so successful.

open-graph

Shadow DOM

Tuesday, March 17th, 2015 | Programming

If you’re using HTML5, you may well have come across templates, which are a way to create reusable code clocks. They can be used in conjunction with the Shadow DOM to create more semantic markup while still adding all the additional goodies in terms of additional CSS and HTML that you would like.

For example, lets say we want to put an email address in a fancy box into a website. The old horrible way of doing it is something like this:

<style>
    #email {
        background: url('images/at.png')
        center left no-repeat;
    }
    #email .label {
        font-size: small;
        text-transform: uppercase;
    }
</style>

<div id="email">
    <div class="outer">
        <div class="label">Email address</div>
        <div>
            john@example.com
        </div>
    </div>
</div>

Look at all that stuff we do not need. Semantically we do not need all those divs. Crawlers don’t need to seem them. Neither do accessibility tools. It would be way nicer if we could mark the page up like this:

<div id="email">john@example.com</div>

Turns out we can! All we need is a little help from templates and the shadow DOM. Lets work from that markup, and put the additional markup into a template tag.

<template id="emailTemplate">
    <style>
        #email {
            padding: 0.5em;
            background: url('images/at.png')
            center left no-repeat;
        }
        #email .label {
            font-size: small;
            text-transform: uppercase;
        }
    </style>
    
    <div id="email">
        <div class="outer">
            <div class="label">Email address</div>
            <div>
                <content></content>
            </div>
        </div>
    </div>
</template>

You will notice that this is basically the same code as we started out with, except now it is in a template tag, and instead of having the email address in there, there is a >content> tag. This acts as a placeholder that the contents of the div will be put into when we combine it all together.

Finally, we use some JavaScript to activate the shadow DOM.

<script>
    var shadow   = document.querySelector('#email').createShadowRoot();
    var template = document.querySelector('#emailTemplate');
    var clone    = document.importNode(template.content, true);
    shadow.appendChild(clone);
</script>

This allows us to add all the additional styling that we had initially, but thanks to the shadow DOM we are able to eliminate a lot of the additional markup in the page itself that made very little sense semantically.

Ember.js

Monday, March 16th, 2015 | Programming

emberjs Ember.js is a JavaScript framework for creating “ambitious web applications” apparently. What that translates to is a JavaScript framework that allows you to get started quickly and have URL-based apps.

It is under heavy active development at time of writing so means that there is plenty of new stuff but also means that the documentation can quickly get out-of-date, so it might take a bit of time fiddling around to get it bootstrapped up and up-and-running. There is a helpful Chrome plugin that fits into the Developer Tools too, though most of the time I spend time looking at the standard console.

Once you are ready to go, things are easy to build. It uses Handlebars, or at least a Handlebars style syntax, so if you have used Handlebars, or even Mustache before then you will probably have a basic idea of what you are doing. You can then layer up pages within each other to build complex applications that can all be bookmarked.

It is designed to work out-of-the-box with Ember Data, which provides instant support for a REST API. If you do not have a REST API, Ember.js claims it is easy to adapt to something else, though I’m sceptical that it is as easy as they claim. It seems to work best if you build the app, and then create a standard REST API to work with it.

I have implemented some simple embedded Ember.js apps for my photo gallery as well as working with it for some more complex projects elsewhere. It is a fun framework to work with, but the documentation is a little parse and it is not quite as flexible as I would like. See the Ember.js website for more information.