Year of Code – The Road to Rachmaninoff

As many people know, I’m a musician as well as developer. I love playing and writing music just as I love creating code. As well as a developer I also work in higher education where I teach programming. First of all, I want to say I fully support initiatives which encourages people to learn to program (such as the Raspberry Pi foundation and code clubs) as I think people (adults and children alike) should be given this opportunity to learn how to program as it not only increases computer literacy, it also provides them with valuable skills which can be used in many aspects of life that involve problem solving and logical methodologies/analysis.

However, I have a serious problem with year of code: and this problem starts with the very top of the yearofcode.org website:

START CODING THIS YEAR
IT’S EASIER THAN YOU THINK

That’s a very bold statement, and potentially very damaging. How hard do people “think” it is? The reason I mention music is because I think it has a lot in common with programming. It is very dangerous to trivialise programming, and the Year of Code programme seems to do just that. This means that people could come into this with a false expectation that, in an afternoon, a month, or even a year they will be able to write an amazing web site or app. It’s like saying to someone “Starting learning the piano this year, it’s easier than you think”, and people may expect to be able to play Rachmaninoff within a year. I’ve been playing for 20 years and I still struggle with Rachmaninoff!

The thing is though, do people think this about learning an instrument? Probably not. Why? Because people already have some awareness about what it takes to learn to play an instrument. However, it still does not stop people from giving up after 3 months claiming “I was rubbish”. I can see this being considerably worse for people getting involved in the “Year of Code” because how far do they expect to come in a year?

Teaching syntax of a programming language is the easy bit, as is teaching the notes on a piano. I can tell you what notes are, and how they relate. Great! Does this give you the skills to be able to play a Rachmaninoff sonata? Eventually. We all started off with the basics. However, to become a great (or even good) developer/musician requires many years of learning and experience, and some would argue (myself included) you never stop learning.

Trivialising programming will just lead to false expectations and disappointment when those expectations aren’t met, and all we will get from it is even more people saying “I can’t do programming” because they have now tried it. Learning to code is a marathon not a sprint, and not only that the goal posts are continually moving as new technology and methodologies come out. I really do encourage people to learn to code, but you must be aware of the challenge that you may face and the amount of time and effort it will take.

Custom Linux Shutdown Scripts

Everyone knows one of the beauties of Linux (and FOSS in general) is the ability to delve in and change functionality for your own requirements. I was having an issue where a standard “poweroff” or “halt” was not shutting the computer down properly, so I needed to write my own scripts to replace them.

On Ubuntu /sbin/poweroff and /sbin/halt are symlinks to /sbin/reboot which is a binary (on debian reboot and poweroff symlink to halt), but the binary is aware of which command is being called, and acts accordingly. This means if you replace one of the symlinks with a script which in turn calls the binary, it will not necessarily perform the action you want (i.e. it will reboot rather than halt or poweroff).

On Ubuntu I solved this problem by creating a /sbin/local directory, copying the binary into there and creating local symlinks.

mkdir /sbin/local
cp /sbin/reboot /sbin/local/reboot
ln -s reboot /sbin/local/poweroff
ln -s reboot /sbin/local/halt

I was then free to replace the /sbin/poweroff, /sbin/halt and /sbin/reboot scripts with my own custom scripts, which were able to call the scripts in /sbin/local and would execute those correctly.

Geolocation Library

In development of my generic geosocial media engine, part of the task was to develop a Geolocaiton library for geospatial calculations. This has since been developed and released at https://github.com/rickogden/Location. This contains a variety of geospatial classes: Point, Line, Multipoint Line, Polygon. On top of these it has a Distance class which is used to output the units of measurement for the distance calculations.

It is very simple to use, you can install it through composer:

 require: "ricklab/location" : "dev-master" 

Once installed it can be used simply as follows:

use Ricklab\Location;

$pointOne = new Location\Point(53.234321, -2.34321);
$pointTwo = $pointOne->getRelativePoint(5, 30, 'miles'); //returns a Point object which is 5 miles away with the bearing of 30 degrees.
$distanceObject = $pointOne->distanceTo($pointTwo);
echo $distanceObject->to('km');

$line = new Location\Line($pointOne, $pointTwo);
echo $line->getBearing(); //returns the bearing of the line
echo $line->getMidPoint(); //returns the mid point of the line
echo $line->length()->to('miles'); //length works identically to distanceTo from a Point object

There are also MultipointLine (for paths rather than straight lines) and Polygon classes. They also have a length method which allows for a total length or perimeter measurement.

The MBR class takes in a Point and a radius around that point. This is useful for when doing SQL geospatial searches as it returns the minimum and maximum latitude and longitude values.

Finally they all implement a toSql() method which converts the SQL to a WKT syntax and implement jsonSerializable. This can be plugged straight into an SQL statement and used to query SQL databases (tested on MySQL but should work also on PostGIS). The jsonSerializable converts the geometry into GeoJSON and can be used with databases like MongoDB.

echo json_encode($pointOne);

Please feel free to use it, and let me know of any bugs which you discover!

Elephpants

PHP 5.4 – The Highlights

ElephpantsI haven’t blogged for ages, so here’s one about the impending release (ie. today) of PHP 5.4! I am just giving a brief introduction to a few features which I think make it a rather interesting release.

Speed

There is going to be a significant speed increase in PHP 5.4 (apparently more so than we got from 5.2-5.3). According to http://news.php.net/php.internals/57760 there is a 20 – 50% increase from 5.3!

Arrays

There are a couple of new features in arrays. The first of all is array creation. You can now create an array using the JavaScript style square-brackets syntax [], rather than having to call the array function.

//in php 5.3 or below
$firstArray = array();
$secondArray = array('foo', 'bar');
$thirdArray = array('foo' => 'fooval', 'bar' => 'barval');

//in php 5.4
$firstArray = [];
$secondArray = ['foo', 'bar'];
$thirdArray = ['foo' => 'fooval', 'bar' => 'barval'];

This will please us JavaScript developers. Also what will please us is the new array dereferencing ability. You’ve long been able to reference an array element from a returned array in JavaScript, but in PHP you’ve had to assign it to a variable and reference from the variable:

//in php 5.3 or below
$arrayVar = $myObj->returnArray();
echo $arrayVar['foo'];

//in php 5.4
echo $myObj->returnArray()['foo'];

So these give us programmers more ways to be lazy! 😀

Class Member Access on Instantiation

Also like JavaScript, PHP 5.4 allows you to call/access a method/property immediately after instantiating the object (without assigning it to a variable).

//in php 5.3 or below
$foo = new Foo();
echo $foo->bar();

//in php 5.4
echo (new Foo)->bar();

Be aware that this instantiates an object, calls the bar() method, and then throws the object away. Generally this is pretty wasteful and often a static method is a more efficient way of doing it. However, it is nice to have this feature.

Traits

And another way we can be lazy is we can use traits. Traits are described as “compiler assisted copy and paste”. In a trait you can include create methods and properties which can be reused in multiple classes. This is not the same as inheritance, which means that you can use multiple traits in a single class. A great example of a use of a trait is for a singleton class (whether or not you agree that singletons should be used at all) which I saw at the PHPUK Conference.

trait Singleton {
  protected static $_instance;

  public static function getInstance() {

    if(self::$_instance == null) {
      self::$_instance = new self();
    }

    return self::$_instance;
  }
}

//now our singleton class, let's call it DatabaseHandler

class DatabaseHandler {
  use Singleton;

  private function __construct() {
    //...
  }
  //...
}

//So now you can do:

$dbh = DatabaseHandler::getInstance();

So, as stated before it is a compiler assisted copy and paste, that means a method in a trait can use private methods in the object, and vice versa. You can use as many traits as you like in a single class (unlike inheritance), and you can even change the visibility and create aliases for trait properties and methods on a per class basis. This is incredibly flexible and allows for increased reuse of code.

Built in Web Server

Finally, PHP 5.4 comes with its very own web server, allowing you to start developing without having a server stack. It is started by executing the PHP CLI binary with the -S switch followed by server:port (eg. localhost:80). Simple as that! It uses your current working directory as the root directory and router can even be specified.

devmachine:project user$ php -S localhost:80

Note: Do not use this in a production environment! Ever!

More Information

I for one am very excited about these features, and really looking forward to teaching and using them in production. As this is a brief overview, I have only highlighted certain new features, for a more in-depth analysis:

  1. Davey Shafik – PHP 5.4: The New Bits, this is the talk that Davey gave at PHPUK2012 (recommended read)
  2. A far more complete overview on King Foo
  3. An overview article on webtutor.pl of PHP 5.4

When Objects Act Like Arrays

I’m a big advocate of object-oriented programming, even though only a few years ago I hated it and thought it was “over engineering”. I don’t believe, however, that object orientation is suitable for every circumstance. Anyway, that’s for another blog post. Objects are great, but not always the best when handling data, particularly things like data collections.

One of the nice things about storing collections of data in arrays rather than objects is the fact that you’re able to easily loop through the collection, and extract data from the collection depending on the position. Sometimes though we may want to manipulate the collection, and store more information than just the data in the collection. This is where SPL comes in.

As of version 5.0 PHP has included the SPL (Standard PHP Library). I am going to look at a couple of interfaces from this library in this blog post: ArrayAccess and SeekableIterator. These interfaces allow us to do a couple of things: SeekableIterator allows us to iterate through the object (eg. a foreach() loop), and the ArrayAccess allows us to extract data from the object as if it was an array. All this in a way that is completely controlled by the programmer.

Definition for the SeekableIterator:

SeekableIterator extends Iterator {
/* Methods */
abstract public void seek ( int $position )

/* Inherited methods */
abstract public mixed Iterator::current ( void )
abstract public scalar Iterator::key ( void )
abstract public void Iterator::next ( void )
abstract public void Iterator::rewind ( void )
abstract public boolean Iterator::valid ( void )
}

Definition for the ArrayAccess:

ArrayAccess {
/* Methods */
abstract public boolean offsetExists ( mixed $offset )
abstract public mixed offsetGet ( mixed $offset )
abstract public void offsetSet ( mixed $offset , mixed $value )
abstract public void offsetUnset ( mixed $offset )
}

The way these work is that they require a variety of methods to appear in the class. With SeekableIterator there is generally a “position” property which is just an integer holding the current position in the collection (so normally defaults to 0). The methods that are required are: seek, current, key, next, rewind and valid. The “seek” moves the position to the number passed in as an argument, “next” method normally increments the position by one, and “rewind” resets the position back to 0. “current” returns the item at which the position property is at, “key” tells you the current value of position and “valid” checks to make sure an item exists at that position. You can then put the object in a foreach loop as if it was an array!

foreach($iterableObject as $item {
     ...
}

ArrayAccess requires fewer methods, and some of them are similar: “offsetExists” is the same as “valid” but rather than getting the position from the internal position property, it is passed in as a parameter. “offsetGet” returns the item at a given position and “offsetSet” sets an item to a given value. You can then treat an object like an array by using standard array notation:

$item = $arrayAccessObject[0];

A single class can implement both of these interfaces without conflict, and SPL contains many more things like this. I have not written this as a tutorial as the PHP Docs are incredibly good on this subject and easy to follow.

http://php.net/manual/en/class.seekableiterator.php
http://php.net/manual/en/class.arrayaccess.php