Archive for the ‘Programming’ Category

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.

PHPNW13

Sunday, October 13th, 2013 | Programming, Tech

phpnw13

Last weekend I headed over to Manchester for PHPNW13.

I really enjoyed last year’s event and came away having learned a lot from it. This year was also quite interesting, though on returning home and reviewing my notes, there is only really one new thing that I want to look into.

Testing select fields in Mocha

Thursday, October 10th, 2013 | Programming

Recently I spent a good twenty minutes tearing my hair out over a JavaScript unit test I was trying to write. The answer turned out to be a difference in the way our Mocha-based DOM differs from how it would running JavaScript in a browser.

For example, let’s say you have a select field.

<select name="test" id="test">
	<option value="">Select an option</option>
	<option value="1">Option 1</option>
	<option value="2">Option 2</option>
</select>

In a browser, the top option would be selected by default, so if you had the following code:

jQuery('#test').val();

It would output a blank value as you would expect. However, run this in Mocha and you will get an undefined or a null. The reason is Mocha doesn’t select the top option by default unless you manually specify it to. So your HTML would have to look like:

<select name="test" id="test">
	<option value="" selected="selected">Select an option</option>
	<option value="1">Option 1</option>
	<option value="2">Option 2</option>
</select>

In which case, it would then return the value as it should.

3 technical challenges we just cannot get right

Saturday, August 3rd, 2013 | Limited, Programming

Having worked on a lot of different projects at a lot of different companies over the years, there are some issues that recur time after time. These are problems that maybe we just don’t have satisfactory patterns for, or developers have a blind spot for. But whatever the reason, they certainly merit more attention in order to reduce how frequently they arise.

Below, I’ve listed three with some suggestions as to how to help mitigate them.

Caching

Caching is essential to good performance in most applications. Remember your ABC – Always Be Caching. Indeed, if you ever want to sound clever in a discussion about system architecture, say “have you thought about caching that?”. Caching is the solution to almost everything. But causes some problems too.

For the non-technical, caching is storing information in short term memory so it can be delivered faster. It’s like remembering things. You probably have a big pile of books at home, and you can’t remember most of them, so for most facts you have to look them up in a book. But you can remember a few things, so for the questions you get asked most, you memorise the facts so you can say them quicker. That’s basically what caching is.

The problem is that when you update something, the cache can end up serving the old content, rather than the new. This results in data being out of date and often results in web applications not appearing correctly because the HTML has updated, but the CSS and JavaScript happens.

Here are a few tips to help mitigate such problems:

  • Have scripts to clear out your various caches. Make sure you know what/where the cache layers are.
  • Understand what cache headers you are serving via you sending via your web server.
  • Have a mechanism for changing files such as stylesheets and JavaScript when you release a new version.
  • Turning caching off on dev environments is fine, but make sure you have it turned on on your staging/pre-production environment so you can spot potential problems.

Timezones

While Britain insisted that time starts and stops in Greenwich, we did allow the rest of the world to make adjustments at hourly (or even half-hourly) intervals based on where they are in the world. This has caused no end of headaches for software developers. Even within one country, one problem that comes up time after time is that systems go wrong when the clocks are changed for daylight savings.

Every six months it all goes wrong every six months and we promise to fix it by the next time the clocks change, but usually never do. Even Apple got it wrong on their iPhone alarm – twice!

Here are a few tips to help mitigate such problems:

  • Set your servers to GMT/UTC and leave them there, regardless of where you are in the world and where DST is in effect or not.
  • Use prper DateTime objects, and specify the timezone.
  • When sending a DateTime string, use an ISO standard and be explicit as to what TimeZone it is in.
  • Unit test DST changes, using a mock system time if required.
  • Perform manual testing on the DST switch.

Load balancing

As systems scale, they inevitably need to spread across multiple processes, applications and bits of hardware. This brings a whole new layer of complexity, though, having to keep everything in sync. It’s very easy to lose consistency and that almost always ends in one thing – say it with me everyone, “race conditions”!

There are two common problems we find in this situation. The first is that one node stops working but the other one is working fine, or maybe something as simple as one node having old code on it. You get intermittent problems but when you try it it works fine or at least works fine 50% of the time. It could be that it is hitting the working node but at other times is hitting the other.

Here are a few tips to help mitigate such problems:

  • Ensure you can (and ideally do automatically) test individual nodes.
  • Use a tool like Chef or Puppet to make sure all your nodes are consistent.
  • Have the ability to easily take out nodes that are not working.
  • Aggregate your logging where possible so you don’t have to tail them on each individual node.

The second is race conditions. This is particularly prevalent when using a master and slave database setup. You will write the update to the master than query for it the results – but because your second query is a read, it will be passed to the slave, which may nor may not have updated yet with the new information.

Here are a few tips to help mitigate such problems:

  • Have the ability to manually specify master or slave so time critical reads can be pointed at the master.
  • Ensuring your staging/pre-production environment load balances everywhere your production environment does so you can spot potential issues.
  • Where possible, rely on one server for the time as different machines can become slightly out of sync.

Composer

Friday, June 28th, 2013 | Programming

These days, you’ll hear a lot of people talking about Composer in a conceited, condescending, and generally irritating way (you are using Composer, right?). It’s very annoying. But despite their best attempts their best efforts to put people off, Composer is actually a really useful tool.

It’s a dependency manager for PHP, allowing you to easily include libraries without having to bundle them in with your application – it’s essentially a package management system for PHP (kind of like PECL, but a lot more useful in many ways).

You can read about it here. Or here, in this blog post. What I should really say is, you can read more about it on the above website. Anyway…

Once you have it installed (and you can install it globally or just on a per project basis as an executable you can run), you can easily install all the depenencies in your project using:

composer install

This installs everything you need based on the project’s composer.json file, that you can save into your version controlled codebase. For example, here is the one I use for a Wing Commander project:

{
	"minimum-stability": "dev",
	"require": {
		"xmeltrut/wing-commander": "*"
	}
}

You can specify as many libraries as you need, and add version requirements for them too. There is also room for a “dev require” section – for example if you are using PHPUnit, you might want to install that library for your dev environment, but not your production clone.

Once you have everything installed, upgrading to the latest version of the libraries is easy:

composer update

Each time you download the libraries, it produces a composer.lock file that you can use to install your dependencies from – this records the version you are using, so you can generate your lock file on your dev environment, test it all works, then ensure your production environment has the same versions of all the libraries.

It also does dependency resolution. So if you try and install something with other dependencies – for example the Wing Commander library uses Flight and Mustache – it will automatically find this and download them too.

You can search for the packages you need on Packagist and while a lot of the libraries you will use are on Github, there is no coupling here – the dependency can specify any repository location and this is all handled transparently.

composer-logo

CSS properties worth remembering

Tuesday, June 4th, 2013 | Limited, Programming

A lot has changed since I wrote my first line of CSS – which is probably going on a decade ago now. Other things have been there all along, but have sometimes been overlooked or neglected. Below is a collection of CSS that it is easy to forget exists.

Selectors

Obviously you can use . # * etc, but there are actually far more options. As well as chaining them (p, div) and specifying them being inside each other (p div) you can also specify they must be the parent (p > div) or immediately after one another (p+div).

As well as checking attributes (input[type=text]) you can also do contains (input[title~=something]) and starting with (input[type|=something]).

We’re probably all familiar with :visited and :hover states, but there are actually dozens you can use – :focus, :first-letter, :first-line, :first-of-type, :last-of-type, :only-child, :empty, :enabled and “checked just to name a few.

Sizing in rem

It’s good practice to use em sizing to make everything relative – that way if a user scales up the page then everything stays in proportion (though modern browsers tend to handle this well anyway). But isn’t it annoying that it stacks? A 2em value inside a 2em value will give you a font size of 4.

You can solve this by using rem. Specifying 2rem will make it 2 x the root (html) element of the document – so you can make it all relevant to that and not worry about nesting.

Gradients

You can add gradients as backgrounds and even create complex patterns with multiple colours starting and stopping at different points.

background-image: linear-gradient(bottom, #22E7D2 12%, #3EFFFC 56%, #2FAB24 100%);

Shadows

It’s simple to add a drop shadow to an element.

box-shadow: 10px 10px 5px #888;

You can add it to text as well.

text-shadow: 2px 2px #ff0000;

Box sizing

Tired of having to work out what width you want something to be, then taking off the padding and the border? Sometimes maybe you don’t even have the option to do that because you want it to be 100% wide. Box sizing to the rescue. Set the box sizing to border and it will calculate the width factoring these properties in.

box-sizing: border-box;

Border radius

Want some nice rounded corners? Easy.

border-radius: 5px;
border-top-left-radius: 3px;
border-bottom-right-radius: 10px;

Clipping

You probably shouldn’t clip as it means you’re sending an image to the browser that is too big and then cutting it down. However, the functionality to do it does exist within CSS>

position:absolute;
clip:rect(0px,70px,100px,0px);

There is a background-clip property too.

Columns

Want to present your text in a series of columns? Theres a property for that.

column-count: 3;
column-gap: 5px;

PMA_Message not found in phpMyAdmin

Thursday, May 2nd, 2013 | Programming, Tech

You may get an error similar to the following in phpMyAdmin.

PHP Fatal error: Class ‘PMA_Message’ not found in /usr/share/phpMyAdmin/libraries/Message.class.php

This is caused when Apache is unable to create a session – perhaps because of a permissions issue on the session folder, or perhaps because you have run out of disk space.

Class constraints in Symfony2

Saturday, March 9th, 2013 | Programming, Tech

Sometimes you need to put a constraint on a whole class, rather than a single value. Duplicate usernames are a good example of this – you don’t want to be able to set a username to one that is already in use – but if it is in use with the user you are currently working on, you don’t want to flag it up as an error!

Lets use that as an example. You have a Username constraint and a UsernameValidator object to do the actual validation. We need to supply the validator an object, so we need to put the following method inside the Username object.

public function getTargets()
{
    return self::CLASS_CONSTRAINT;
}

This will turn the first parameter in our isValid function in the UsernameValidator class to an object.

public function isValid($user, Constraint $constraint)

Finally, you can call the constraint from your YAML validation file.

User:
    constraints:
        - nocs:UniqueUsername: ~

Normally, under user you would have getters and properties – but here we’re adding a new section named “constraints” which lists all the class constraints.

The Psychologist’s View of UX Design

Friday, March 8th, 2013 | Limited, Programming

If you’re interested in good user experience design (and who isn’t, right!) then it might be good to get the perspective of someone who actually studies users – someone like a psychologist for example. Luckily, one such psychologist is interested in such matters and has written rather a good article about it.

Over at UX Magazine, Susan Weinschenk has written The Psychologist’s View of UX Design and it provides a very useful breakdown of a lot of UX areas and how she views them. Well worth a read.

Validation in Symfony2 unit tests

Sunday, March 3rd, 2013 | Programming, Tech

Want to use the Validation module in your Symfony2 unit tests? No problem, thanks to the ValidatorFactory, it’s relatively straight forward.

use Symfony\Component\Validator\ValidatorFactory;

class ExampleTest extends \PHPUnit_Framework_TestCase
{
    public function testSomething()
    {
        $validator = ValidatorFactory::buildDefault()->getValidator();
    }
}

Simply include the ValidatorFactory namespace and then use the class and it’s default values method to deliver you a validator, which you can then validate your objects against just as if it was in a controller.