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

Installation of Memcache in PHP on Ubuntu/Debian

Happy new year all! Just a quick post about how to install Memcache in PHP on an Ubuntu or Debian server (I think it will apply to Redhat based servers, just substitute the apt-get for yum).

Log on to your server as root (either directly or using sudo su), then install the Memcache daemon through apt:

apt-get install memcached

Once installed you need to install the Memcache module into PHP. This is done through PECL which in turn is installed through PEAR. When they are both installed, you need to run the command:

pecl install memcache

This will install the memcache extension, and once done will tell you to add the the line “extension=memcache.so” into your php.ini file. I prefer keeping these in separate files (so that the php.ini file can be updated). The easy way to do this is:

echo "extension=memcache.so" > /etc/php5/conf.d/memcache.ini

And finally, reload Apache

/etc/init.d/apache2 reload

If successful, Memcache will now appear in your phpinfo().

PHPNW10 – An Overview

I had a fantastic time at phpnw10 this year. Met loads of old friends, and made a few new ones. The main conference kicked off on Saturday morning with a keynote by Lorna Mitchell entitled “Teach a man to fish”. This was about how team training is important with proper feedback mechanisms which enable a developer (and a team) to learn from their work and give them the skills to teach themselves further. Following that I went to see Derick Rethans giving a talk on geolocation within PHP. This gave me a great insight into how geolocation/mapping works online and has given me some food for thought for my MSc. After, I headed back to the main track to see Ian Barber speaking about debugging. I find that this is the sort of talk I can’t get enough of, and discovered a couple of cool new tools to help with debugging on top of the existing ones I already use.

After lunch I saw Michelangelo Van Dam talking about unit testing within ZF. Like everything with ZF, it seemed a lot easier than I thought it might be. Then there was another ZF talk in the same room by Rowan Merewood who, as always, gave a rather entertaining talk. It was about Zend_Acl and used real-world examples (ship classes from Star Trek) to demonstrate how they work.

Scott MacVicar gave a really interesting talk on HipHop for PHP, allowing PHP code to be compiled. He went through the process of using it, what the current limitations are and the plans for the future. As this was Scott, heckling was aplenty, and made this talk very enjoyable! Then it was back to the main track for the final session: The Framework Shootout, a panel session chaired by Marcus Deglos. Although there were no definitive conclusions that came out from the panel, it was very interesting to see different people’s take on things, and the strengths and weaknesses of a variety of frameworks.

Overall it was an excellent event with excellent attendance! However we have a bit of a dilemma now. We have reached the capacity of this venue. This means that if we want to expand we will need to find a new one. If you have any thoughts/ideas/recommendations on not only venues around Manchester, but how we can expand further to increase the impact of the PHPNW group, please let me know! Finally I would like to thank Jeremy Coates and all the helpers on the day, the event ran fantastically smoothly and it was all down to you, thanks everyone!