A small redesign of mhn.me

Out with the old

old

In with the new

new

Go check it out!

Why? Well, I was never really happy with the original; I designed it to have work samples and articles, and when I took those away it looked a bit bare. It also didn’t show off my love of typography, due to the (at the time) limited number of fonts on Google fonts. After recently perusing the available fonts again, I was impressed with the variety and quality, and started toying around to see what I could come up with. After a couple of hours I had a new website.

Google fonts

I sincerely recommend Google fonts to anyone looking to design a website. It massively reduces the work involved in finding fonts with web friendly licenses, and exporting to all the different file types (for pretty much universal support you’ll need: WOFF, EOT, SVG and TTF).

It also reduces load times by:

  • only loading the file format that the user’s browser supports;
  • linking to the same source for users all across the web, meaning that the more popular fonts are likely to be in their browser cache already; and
  • it’s on a large CDN with good uptime, and servers in every continent meaning it’s way faster than what my measly Linode virtual machine can serve

As a bonus, it’s insanely easy to use. Pick your font, choose the variations you want (eg. you may not need the italics version, so you can reduce download sizes by not including it) and copy the <link> tag they show in to your HTML (or as I do, embed it as an @import in your existing styles, just to keep the HTML tidy).

A clarification on “There’s only ONE exchange rate”

Today an article about exchange rates cropped up on hacker news, and caused quite a bit of controversy and confusion, so I want to clarify some of the things said, as well as fix some of the incorrect information (including the title, which is factually incorrect).

The original article.

Some formalities first

Firstly, I want to explain why you should listen to me: I work as a developer for an FX brokerage in London, UK. I’ve been working here for under a year, but I’ve been actively applying all of what I’m about to explain.

I don’t represent the company I work for on this blog.

Why the post is wrong

The title of the blog post is “There’s only ONE exchange rate. Any others are just works of fiction.” which is incorrect, no matter what interpretation of it you use. They mention in the post that what they mean by one exchange rate is the mid-market rate, which only exists as a tool to simplify graphs. There are actually 2 exchange rates: the bid, and the offer, and the difference is called a spread.

Let’s create a fictional scenario to explain what the spread is:

Say you have 1,000 Euros (EUR), and you’re interested in swapping it for United States Dollars (USD). In this situation you’re putting your money up for bid, wanting an offer from a bank, or a brokerage. Unfortunately for you, there’s been a lot of speculation recently about the Euro collapsing due to an economic crisis in Germany, so people are more interested in keeping their USDs than selling them for Euros. This means that what you might want for your EUR is going to be less than what other people are willing to offer, because they are worried that it will soon be worthless.

Now think of it from the other side. You have 1,000 USD and you’re interested in swapping it for EUR. Because everyone’s so interested in buying USD and selling EUR, it means that you’re able to set your bid at a higher figure, and the market will still take it off your hands.

The mid-market in this case was never on the table, it was simply a figure that’s in the middle of the bid/offer spread for EUR/USD. All currency pairs that aren’t pegged to each other have this spread, with some having a larger spread than others (this depends on how volatile the market is for those pairs).

Remember, there’s no regulative authority dictating what currency is worth what, it’s purely dictated by market demands.

The spread your bank offered you

So the market always has a spread, but that spread is not the same as the one your bank (or brokerage) offered to you. What happens is that they will take that spread, and apply an additional percentage to each side (eg. +5% on the buy, -5% on the sell for EUR/USD), which they pocket. Some places (high street banks usually), will do this and add an additional fee on top of that.

Who should you work with?

That’s entirely up to you, I’m not pushing an agenda. I have no real opinion of the company who wrote the original article, I just wanted to clear up some mistakes.

Fear driven development

This isn’t about yet another development cycle technique, it’s about motivation and specifically what motivates me. There are two main factors that decide how productive I am: availability of coffee, and fear.

The former is easy to explain: I drink an extremely strong coffee (or 10) and suddenly I’m alert, my concentration improves, and I can work away on whatever, so long as it doesn’t involve a steady hand (remember kids: no coffee before shaving your balls). The latter motivating factor—fear—helps me decide what to work on.

When I’m at home, I have no fear, so when I drink my coffee I have about a 75% chance that I’ll either be a twitchy, tumultuous gamer, or I’ll be feverishly browsing reddit as if it’s the last time I’ll ever see it.

When I’m at the office, I’m fucking terrified that any second now someone will catch on that I have no idea what I’m doing and they’ll fire me, so my paranoia drives me to stay focused. I take (extremely) regular bathroom breaks thanks to my coffee addiction, but other than that, I’m focused on my task list about 95% of the time. This fear is extremely unpleasant of course, and I’ve lost countless hours of sleep thinking about how I’m going to get the sack the next day. The very reason I’m writing this right now is because I have my first review tomorrow, and I’m not sure how it’s going to go.

I don’t really deserve to be where I am in life, it’s all been one fluke after another and some day someone will catch on and put me back where I belong. Until that time I’ll live in fear that one day someone will actually spend some time looking at what I’ve really done (hint: not much) then call me out on it. Until then though, let’s pretend nothing’s wrong; I’d rather live in fear and be in over my head than back where I was before I got in to development work.

How to use LESS CSS and Symfony 2 in harmony

Assetic, the assets manager used by Symfony (and a really great tool which is heavily influenced by Python’s webassets library) has built in functionality for passing your files through a filter in order to generate new output. Using it with LESS files is a snap, as it already comes with 2 filters for generating CSS files from LESS files. One filter works with less.js (the official compiler) through node.js. Another method, common when you’re only able to work with PHP, is to use lessphp.

Using the official compiler

Of course, this is the recommended method. If you have root access to your server it’s also very easy to set up.

Install node.js, npm and less

Install node.js. The latest version of node.js now comes with npm already, but run npm after installation to make sure. If it doesn’t exist, then install npm:

$ curl http://npmjs.org/install.sh | sh

Now install the less compiler:

$ npm install less

Now you need to find where your node.js binary and modules are installed. Here’s where they were for me (Arch Linux and Debian):

Binary: /usr/local/bin/node

Modules: /usr/local/lib/node_modules/

I’ve seen the modules in /usr/local/lib/node/ before, though it’s possible this is an outdated practice.

Configure it’s use in your project

Open up your project’s configuration file in app/config/config.yml and add the following:

assetic:
    filters:
        cssrewrite: ~
        less:
            node: /usr/local/bin/node
            node_paths: [/usr/local/lib/node_modules]
            apply_to: "\.less$"

The apply_to parameter isn’t essential, but it does mean that you don’t need to apply the filter manually, it’ll automatically apply it to any files ending in .less.

Now in your templates all you need to do is:

Twig:

{% stylesheets 'path/to/files.less' %}
  <link rel="stylesheet" href="{{ assets_url }}" />
{% endstylesheets %}

PHP:

<?php foreach ($view['assetic']->stylesheets('path/to/files.less') as $url): ?>
  <link rel="stylesheet" href="<?php echo $view->escape($url) ?>" />
<?php endforeach ?>

Using the lessphp compiler

In the root of your project you have a deps file. Add the following to it:

[lessphp]
    git=https://github.com/leafo/lessphp.git
    target=/lessphp
    version=v0.3.3

From the command line run:

$ bin/vendors install

Open up your project’s configuration file in app/config/config.yml and add the following:

assetic:
    filters:
        cssrewrite: ~
        lessphp:
            file: %kernel.root_dir%/../vendor/lessphp/lessc.inc.php
            apply_to: "\.less$"

The apply_to parameter isn’t essential, but it does mean that you don’t need to apply the filter manually, it’ll automatically apply it to any files ending in .less.

Now in your templates all you need to do is:

Twig:

{% stylesheets 'path/to/files.less' %}
  <link rel="stylesheet" href="{{ assets_url }}" />
{% endstylesheets %}

PHP:

<?php foreach ($view['assetic']->stylesheets('path/to/files.less') as $url): ?>
  <link rel="stylesheet" href="<?php echo $view->escape($url) ?>" />
<?php endforeach ?>

Before and after XMLHttpRequest

Although people think Microsoft has been holding the future of the web back with it’s poor support for the web standards, they did get one thing right, XMLHttpRequest, which has apparently spawned an entirely new version of the web (Web 2.0). Before Microsoft revolutionized communication between server and browser, how did people achieve the same level of communication between the user’s browser and the webmaster’s server that we take for granted today? Well, the web was built by hackers, and there are some clever ones out there who faced this problem long before Microsoft came up with their solution.

Use images

Javascript introduced an Image object in 1996. With this object you can set the image source and the browser will request the image from that source.

var image = new Image;
image.src = "http://example.com/request"; // new request is made

A limitation for this was that the data returned needed to be a valid image, and up until recently (with the advent of canvas), javascript was unable to read the raw image data. This means that you can’t return any meaningful data within the image that can be read. This meant that all communication to the server was one way, which simply wouldn’t do, so hacks were found:

The first, easiest to use approach was to actually return an image of text, which you could then embed in the page for the user to see. This works well if you’re after something simple like showing their name after they’re logged in, but isn’t ideal when the data is more complex, nor is it friendly to the user.

A second approach was to make the call with the image, then the server will set a cookie with the data to return, which can then be read from javascript. One problem with this method was it’s reliance on a cookie, something that users were wary of back in 1996.

Another alternative was to create and return an actual image from the server and use it’s dimensions to determine what to output to the user. For example if the user has tried to post a comment you could do something like:

var SUCCESS                = 1,
    ERROR_POST_DELETED     = 2,
    ERROR_INVALID_PASSWORD = 3;
 
var requestImage = new Image;
 
// ...snip...
 
if (requestImage.width == SUCCESS) showUserComment(comment);
else showCommentPostError(requestImage.width);

The maximum width or height of a GIF image is 65,535 (the width and height are stored in the header of the file as 16-bit binary numbers, with the largest 16-bit binary number being 65,535). If it wasn’t for this limitation, then it might have been possible to store much more data in the width of a GIF, because it compresses really well (thanks to it’s use of LZW compression). In fact, a GIF that’s 60,000px wide, 1px tall and the same colour throughout is only 370 bytes.

With the rise of iframes came the downfall of image hacks

By the time the new millennium had come around, frames and iframes were in popular use. These had mostly solved the issues that people were trying to fix with the image hacks above, specifically you no longer needed to reload the entire page to update a particular area of the website. Javascript could still be used to change the location of a frame, and you could now read the data within the frame. This lead to developers using hidden frames to submit and request data to and from the server. They could then read the data that was returned in the frame and determine what to do with that information.

This was a much bigger leap than the XMLHttpRequest in terms of functionality because it introduced the ability for the server to actually return data. All XMLHttpRequest did was give a concrete, cross browser implementation of something that developers had been hacking in to their code since the late 90′s.

On to the present

Now we want push data from the server to the browser. There’s an official standards for this, and implementations of WebSockets/Server-sent events already exist in most modern browsers (currently by Chrome, Firefox and IE10), but until people are no longer using IE9 or less, and until Opera has an up-to-date implementation, we’re stuck using hacks. The most popular current techniques are referred to as Comet techniques:

AJAX long polling

With this technique you would use javascript to make an AJAX request, with a really high timeout, then the server can keep that connection open and respond to it if anything needs pushed to the user. This technique isn’t wise when using the popular Apache/PHP combo because not only will Apache dedicate a worker to the request for it’s entire duration (which could be minutes if you’re building something like a chat application), but there will also be a PHP process running for the duration of that request too.

Flash XMLSocket

This is a little trickier to implement, but has a huge performance benefit. The gist of it is that it opens a TCP socket connection with the server, rather than a HTTP request, so you can use something lighter and more dedicated to the role to respond to the user (ie. not a web server). This method is popular with Flash based games and chat systems, because there isn’t much in the way of overhead that you don’t create yourself, and you can use anything from a Java applet to node.js to pick up the connection and respond from the server side, with a single instance running and listening to the port. The main downfall of this is that many server providers block most ports for security, so unless you’re running a dedicated server or virtual server then you’ll need to check that additional ports are actually available.

The future

The future is beginning to look rosy for push notifications. With implementations of WebSockets and Server-sent events already existing, it shouldn’t be long before the general population is using browsers that support these technologies. Extremely feature rich, native-like applications are definitely on their way.

What I would like to see now is a standard for TCP and UDP connections from the browser without the use of plugins. In combination with WebGL for GPU rendering, you could have real-time rendering from a particle simulator on the other side of the planet with no need to install any software other than a web browser. Or better yet, counter-strike in your browser :)

Starting small: Next/Previous links in SilverStripe

I’ve always wanted to contribute some open source software back in to the community for the thousands of hours it’s saved me over the years. I have lots of big ideas that I’ve accumulated that are sort of scary to think about because of their scale, so I’ve decided that I’ll start off small. Here’s a dead simple method you can add to your Page_Controller class in SilverStripe CMS to get the next/previous item from the parent. If it gets to the end, it loops round to get the first item, and the first loops over to the last item.

Add the following block of code to your Page’s controller (the class that extends Page_Controller)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
 * Gets the next/previous content item. If one isn't found then gets the
 * first content item if searching for next, or last content item if
 * searching for previous
 *
 * @param string $mode 'next' for next; 'prev' for previous
 */
public function PrevNextPage($mode = 'next') {
    switch ($mode) {
        case 'prev':
            $where = "ParentID = ($this->ParentID) AND Sort < ($this->Sort)";
            $sort = "Sort DESC";
            break;
 
        case 'next':
        default:
            $where = "ParentID = ($this->ParentID) AND Sort > ($this->Sort)";
            $sort = "Sort ASC";
            break;
    }
 
    $result = DataObject::get("SiteTree", $where, $sort, null, 1);
    if (!empty($result)) return $result;
 
    $resetWhere = "ParentID = ($this->ParentID)";
    $result = DataObject::get("SiteTree", $resetWhere, $sort, null, 1);
    return $result;
}

Use it like so in your templates:

1
2
3
4
5
6
<% control PrevNextPage(prev) %>
    <p class="prev"><a href="$Link">&larr; Previous</a></p>
<% end_control %>
<% control PrevNextPage(next) %>
    <p class="next"><a href="$Link">Next &rarr;</a></p>
<% end_control %>

This was tested on v2.4.6 of SilverStripe. I doubt I’ll be maintaining newer versions as this was for my first and probably last venture in to SilverStripe.

I’ve posted it under the Creative Commons 1.0 license which you can view in my footer.

Web design without Photoshop

Lately I’ve been messing about with designs for different websites and I’ve been coming to the realisation that fewer parts of a website actually require images and the parts that do may be achievable without an image editor.

Okay, so the 2 parts of a website that I haven’t figured out how to remove image editing from are the favicon and the logo. The logo can possibly be achieved if the company has existing branding and just happens to have a transparent PNG of their logo that’s the right size for a website. The favicon though−unless you’re really lucky−will require image editing.

Okay, so you’ve got the logo and the favicon, now it’s time to design the website. First, you’ll want to create the HTML for the main template and add the home page content. HTML5 Boilerplate is a great starting point for this. It has a lot of sensible defaults that are easy to override if it’s not your preferred way of doing things.

Once you’ve got your semantic markup, it’s easy to add some CSS to get the site structure. Maybe you even have a standard structure that you’ll use, or you’ll be using a CSS framework like Blueprint.

High 5, you have a semantic website with basic structure. Now let’s prettify the shit out of it. You have a logo, I’m assuming the company has some sort of colour and branding guidelines, bonus! If not, then you can get your inspiration from Colour lovers.

Okay so now you have your colours, you can add extra kapow to your website by using a none-web font. Check out Google Web Fonts for an easy way to do this.

Now, you have awesome colours and a sweet font or 2, this is where it gets tricky, you need to somehow use those colours, your nice semantic layout and those sweet fonts, you need to think of ways to combine them.

This red would look great as a background to the navigation. If we add a CSS transition to this darker red, that would look nice.

We could use this grey and this darker grey as a gradient for the footer, then use text shadows to make it look like the mac I’m using; awesome!

You get the picture. For me this is a thought process that I can’t easily describe but it goes a bit like this: you stare at a boring part of the website, then an awesome idea hits you, then you change it again because that was a terrible idea, and so on.

Now, you being the socially aware person that you are, you decide you need some FB/Twitter links in the footer and it’d be great if they could include icons. You could be really cool and use SVG for them, or you can just go to Smashing Magazine and download whatever set takes your fancy. This will work for 99% of icons you’ll ever need.

As for the actual content, as I’m sure it’ll require images, if they’re photos that need cropped and resized you could use one of the many free online tools for cropping and resizing images.

Thinking and designing this way helps force me to focus on creating designs that work better as a website, rather than a pretty image in Photoshop. You can actually test how it reacts whilst you’re interacting with it. Designing this way will require image software at some (or many) points, but doing the design in Photoshop then converting it to HTML and CSS is backwards; websites have too many points of interactivity to be able to emulate in photoshop.

PHP as a templating language

Many templating languages have been built for PHP (Twig, Smarty, Dwoo, etc.). These languages will have a subset of the features of PHP useful for formatting text and some basic programming (looping, counters, basic arithmetic). Here I’ll offer some of the more common arguments in favour of templating languages and why I think they’re wrong. I’ll be using Smarty as a demonstration language because it’s the most popular, and the one I have the most experience with.

Front-end developers should never have to deal with PHP

This is the most common argument, usually backed by up by saying that it offers the front-end person a cleaner syntax/easier to use language for their uses (I’ll get back to this) and that it reduces the amount of opportunities that a front-end person can accidentally break the backend of the code. Firstly, let me demonstrate how a front-end person can use PHP in Smarty, thus negating the supposed risk of them not having access to it.

{php}die('Whoops!');{/php}

Whoops, indeed. If you’re using some sort of method for separating your logic from your output (for example, an MVC framework) and you’re using OOP (because it’s 2012 and anyone still using procedural code and global variables is a fucking tool, or working on a legacy system, which will already have it’s own way of doing things), then the front-end person will never have access to the database or any other objects that you don’t explicitly pass from the controller to the view, regardless of what language the view uses.

The syntax is cleaner

Not always. Compare

{$smarty.now|date_format:'%Y-%m-%d %H:%M:%S'}

With

date('Y-m-d H:i:s');

 I know it’s a contrived example, but there are plenty like it, and this one came straight from the docs.

I started out as a front-end developer and I can’t really describe how frustrating Smarty’s syntax was for me. No syntax highlighting, a warning in my IDE for every variable or control structure I used, problems with javascript (especially passing variables from PHP to javascript, you have to decide whether to escape the whole javascript block and unescape for the variables like so):

{literal}
    <script type="text/javascript">
        function init() {
            var username = "{/literal}{$username}{literal}";
            // ...
        }
    </script>
{/literal}

Or you used the {rdelim} and {ldelim} predefined constants to add your braces:

<script type="text/javascript">
    function init() {ldelim}
        var username = "{$username}";
        // ...
    {rdelim}
</script>

There is an option to change the Smarty opening/closing braces to something more sensible, but it uses braces by default, so that’s what most people use.

There is one thing I like about Smarty though: because it’s a domain specific language it makes it easy to to manipulate string variables, thanks to it’s variable modifiers. For example:

{$title|truncate:40:"..."}

Will truncate the string to 40 characters and add a trailing ‘…’ if the title is longer than 40 characters. The (raw) PHP is more complicated:

echo (strlen($title) < 40) ? $title : substr(0, 40, $title) . '...';

There’s also the option to truncate from the middle of the string, or from the boundary of a word, which gets much more complex in PHP.

I don’t feel that this justifies an entirely new language though. There are template libraries out there that use PHP as the templating language, and have useful helper functions. I’ll demonstrate with Zend\View (I especially like the currency helper here)

echo $this->currency($value);
// could be € 1.234,56 or £1234.56, etc. depending on locale

With Zend\View it's also easy to add your own helpers, which could be things that are specific to the project, so you could create a helper for calculating which posts are popular based on frequency of replies.

Is it really necessary to add yet another language to an already language abundant stack, especially when PHP is so close to getting it right? Wouldn't it be great if your back-end developers could easily read how the front-end developers are using the data given to them without having to scour the Smarty docs, and wouldn't it be nice for the front-end developers to have the auto-completion, PHPDoc for the variables, and be able to read the code that defines the variable so they can understand where it comes from?

I know that I never benefited from templating languages in PHP, and after many years of web development, I'm still waiting for the case where it is beneficial to anyone around me.