The PHP 5.4 Features You'll Actually Use

D33d8bdd9096c80b8d1acca8d28410b5?s=47 Lorna Mitchell
September 01, 2012

The PHP 5.4 Features You'll Actually Use

Slides from my CakeFest talk in Manchester 2012

D33d8bdd9096c80b8d1acca8d28410b5?s=128

Lorna Mitchell

September 01, 2012
Tweet

Transcript

  1. The PHP 5.4 Features You Will Actually Use

  2. About Me • Lorna Jane Mitchell • PHP Consultant/Developer •

    Author of PHP Master • Twitter: @lornajane • Website: http://lornajane.net
  3. About PHP 5.4 • New features • Traits • Built-in

    webserver • New array syntax and dereferencing • And more! • Removed some nonsense • This talk covers the best bits* * an entirely subjective selection
  4. Start With The Easy Bit

  5. New Array Syntax

  6. Array Syntax We had this: $game[] = 'paper'; $game[] =

    'scissors'; $game[] = 'stone'; print_r($game); $game[0] = 'paper'; $game[1] = 'scissors'; $game[2] = 'stone'; print_r($game);
  7. Array Syntax Or this: $game = array('stone', 'paper', 'scissors'); print_r($game);

    $game = array(0 => 'stone', 1 => 'paper', 2 => 'scissors'); print_r($game);
  8. Array Syntax Now we can do: $game = ['scissors', 'stone',

    'paper']; print_r($game); $game = [0 => 'scissors', 1 => 'stone', 2 => 'paper']; print_r($game);
  9. Array Dereferencing

  10. Array Dereferencing When an array is returned, immediately pick an

    element from it function getList() { return ['Grumpy', 'Sleepy', 'Bashful', 'Doc']; } // grab first item from list $item = getList()[0]; echo $item; // Grumpy;
  11. PHP 5.4 Stealth Feature

  12. PHP 5.4 Is Faster

  13. PHP Versions Speed Comparison Benchmarks made using: • Newly-compiled vanilla

    PHP binaries • The bench.php script in the PHP source tree • A rather average laptop • 10 runs per version, then averaged
  14. PHP Versions Speed Comparison

  15. PHP Versions Speed Comparison

  16. PHP Versions Speed Comparison

  17. PHP Versions Speed Comparison

  18. Traits

  19. Traits Re-usable groups of methods, in languages with single inheritance.

    • Declare a trait, it looks like a class • Add the trait to your class using the use keyword • Methods are available!
  20. Simplest Trait Example <?php trait Audit { public function getAuditTrail()

    { return "nothing changed"; } } class Princess { use Audit; // General princess class description: // soldering, tree climbing, the usual } $daisy = new Princess(); echo $daisy->getAuditTrail();
  21. Other Trait Trivia • They can be aliased when used

    • There are rules about resolving naming clashes • Traits can include properties • Traits can include abstract methods • Traits can themselves make use of other traits
  22. Built In Webserver

  23. Built In Webserver Built in application server for PHP 5.4

    • Simple • Lightweight • Development use only From the manual: "Requests are served sequentially." http://lrnja.net/NQoXsh
  24. Webserver Examples Start a simple server on a port number

    of your choice php -S localhost:8080 http://localhost:8080
  25. Webserver Examples Change the hostname: php -S dev.project.local:8080 http://dev.project.local:8080

  26. Webserver Examples Specify the docroot php -S localhost:8080 -t /var/www/superproject

    Specify which php.ini to use (default: none) php -S localhost:8080 -c php.ini-development
  27. Webserver Examples Use a routing file (example from http://lrnja.net/LigI4U) <?php

    if (file_exists(__DIR__ . '/' . $_SERVER['REQUEST_URI'])) { return false; // serve the requested resource as-is } else { include_once 'index.php'; } routing.php php -S localhost:8080 routing.php The webserver runs routing.php before entering the requested script. This example serves any existing resource, or routes to index.php
  28. Session Upload Progress

  29. Session Upload Progress File upload progress, written to the session

    at intervals Useful for user feedback, e.g. shiny new HTML5 progress bars!
  30. Tracking Upload Progress User starts uploading file in the usual

    way <form name="upload" method="post" enctype="multipart/form-data"> <input type="hidden" name="<?php echo ini_get("session.upload_progress.name"); ?>" value="123" /> File: <input type="file" id="file1" name="file1" /> <input type="submit" value="start upload" /> </form>
  31. Tracking Upload Progress In a separate file, we can check

    the relevant session variables to see how the upload is going: http://lrnja.net/Lhs7jJ array(1) { ["upload_progress_123"]=> array(5) { ["start_time"]=> int(1340542011) ["content_length"]=> int(1529158981) ["bytes_processed"]=> int(1386660589) ["done"]=> bool(false) ["files"]=> array(1) { [0]=> array(7) { ... } } } }
  32. Anonymous Functions, __invoke and the Callable Typehint

  33. Typehinting We can typehint in PHP, on: • Classes •

    Interfaces • Arrays
  34. Typehinting We can typehint in PHP, on: • Classes •

    Interfaces • Arrays • ... and now Callable Callable denotes anything that can be called - e.g. a closure, callback or invokable object
  35. Anonymous Functions • Literally functions with no name • More

    convenient than create_function() Example: $ping = function() { echo "ping!"; }; $ping(); // ping!
  36. Callable Examples function sparkles(Callable $func) { $func(); return "fairy dust";

    } $ping = function() { echo "ping!"; }; $pong = "pong"; echo sparkles($ping); // ping!fairy dust echo sparkles($pong); Catchable fatal error: Argument 1 passed to sparkles() must be callable, string given, called in /home/lorna/.../callable.php on line 16 and defined in /home/lorna/.../callable.php on line 10
  37. Callable Examples function sparkles(Callable $func) { $func(); return "fairy dust";

    } class Butterfly { public function __invoke() { echo "flutter"; } } $bee = new Butterfly(); echo sparkles($bee); // flutterfairy dust
  38. JsonSerializable

  39. Sleep and Wakeup When we serialize() or unserialize() an object,

    PHP provides "magic methods" for us to hook into (this isn’t new): • __sleep() to specify which fields should be serialized • __wakeup() to perform any operations needed to complete an object when it is unserialized This gives us the same feature for when we JSON something
  40. The JsonSerializable Interface From the manual: JsonSerializable { abstract public

    mixed jsonSerialize () } Objects implementing the JsonSerializable interface can control how they are represented in JSON when they are passed to json_encode()
  41. JsonSerializable Example class gardenObject implements JsonSerializable { public function jsonSerialize()

    { unset($this->herbs); return $this; } } $garden = new gardenObject(); $garden->flowers = array("clematis", "geranium", "hydrangea"); $garden->herbs = array("mint", "sage", "chives", "rosemary"); $garden->fruit = array("apple", "rhubarb"); echo json_encode($garden); {"flowers":["clematis","geranium","hydrangea"],"fruit" :["apple","rhubarb"]}
  42. No More Nonsense

  43. Removed Features • register_globals • register_long_arrays • safe_mode • magic_quotes

    • allow_call_time_pass_reference • y2k_compliance • ereg* functions
  44. Upgrading to PHP 5.4 • Turn on E_DEPRECATED in PHP

    5.3 • Warns when you use features which are gone in 5.4 • Test with the PHP 5.4 webserver
  45. PHP 5.4

  46. Did I Mention it’s Faster?

  47. The PHP 5.4 Features I’ll Actually Use • Short array

    syntax • Traits • Built in webserver • Upload progress • Callable • JsonSerializable
  48. Questions?

  49. Resources All in a single bundle for you: http://lrnja.net/KOouXv

  50. Thanks! https://joind.in/6738 @lornajane http://lornajane.net