Upgrade to Pro — share decks privately, control downloads, hide ads and more …

New Wave PHP

New Wave PHP

Features arriving in the most recent versions of PHP, along with gotchas and advice for upgrading your existing platforms.

Lorna Mitchell

February 15, 2015
Tweet

More Decks by Lorna Mitchell

Other Decks in Technology

Transcript

  1. New Wave PHP
    Lorna Mitchell, PHPUK 2015
    (these slides are already online
    http://lrnja.net/new-wave-php)

    View Slide

  2. Recent Versions of PHP

    View Slide

  3. New Wave PHP
    Data from http://w3techs.com

    View Slide

  4. Changes in PHP

    View Slide

  5. Register Globals is Gone (5.4)
    Upgrade PHP and see many undefined (simple) variables.
    To fix each undefined variable:
    •replace $username with $_GET['username'] or
    $_POST['username'] in each case

    View Slide

  6. Echo Shortcut (5.4)
    PHP 5.4 removes short_open_tag config option
    • is never valid - s//•= is always valid
    = is the same as:

    View Slide

  7. Error Reporting: E_STRICT
    E_ALL includes E_STRICT in PHP 5.4+
    You can either:
    1.Fix your errors
    2.Turn it off again using E_ALL & ~E_STRICT

    View Slide

  8. Timezone Settings (5.4)
    PHP refuses to guess the timezone and will warn you.
    It is not safe to rely on the system's timezone settings.
    You are *required* to use the date.timezone setting or the
    date_default_timezone_set() function.
    In case you used any of those methods and you are still getting this
    warning, you most likely misspelled the timezone identifier.
    Fix it by setting date.timezone in php.ini:
    date.timezone = "Europe/London"

    View Slide

  9. Call Time Pass By Reference
    PHP Fatal error: Call-time pass-by-reference has been removed
    This error says "don't pass references in when the function didn't
    expect them, you fool"

    View Slide

  10. Call Time Pass By Reference
    You can pass by reference. Declare function:
    1 function inspire(&$person) {
    2 // be inspiring
    3 }
    Call with just $ and not &
    1 inspire($current_user);

    View Slide

  11. Traits (5.4)
    Traits are building blocks for classes
    Traits can:
    •build on one another
    •be used together
    •are inherited by child classes

    View Slide

  12. Traits
    1 namespace Silex\Application;
    2 use Monolog\Logger;
    3
    4 trait MonologTrait {
    5 public function log($message, $context = array(), $level) {
    6 return $this['monolog']->addRecord(
    7 $level, $message, $context);
    8 }
    9 }

    View Slide

  13. Traits
    To use a trait:
    1 use Silex\Application;
    2 class MyApplication extends Application {
    3 use Application\MonologTrait;
    4
    5 public function myAwesomeMethod() {
    6 ...
    7 $this->log("Something happened");
    8 ...

    View Slide

  14. DateTimeImmutable (5.5)
    DateTime is awesome
    1 $important_date = new DateTime();
    2 print_r($important_date);
    3 $result = $important_date->add(new DateInterval('P4D'));
    4 print_r($important_date);
    5 print_r($result);
    DateTime Object ( [date] => 2015-02-14 20:28:20 ... )
    DateTime Object ( [date] => 2015-02-18 20:28:20 ... )
    DateTime Object ( [date] => 2015-02-18 20:28:20 ... )

    View Slide

  15. DateTimeImmutable
    DateTimeImmutable does what you'd expect
    1 $important_date = new DateTimeImmutable();
    2 print_r($important_date);
    3 $result = $important_date->add(new DateInterval('P4D'));
    4 print_r($important_date);
    5 print_r($result);
    DateTime Object ( [date] => 2015-02-14 20:28:20 ... )
    DateTime Object ( [date] => 2015-02-14 20:28:20 ... )
    DateTime Object ( [date] => 2015-02-18 20:28:20 ... )

    View Slide

  16. Easy Password Hashing (5.5)
    Strongly hash your passwords with a built-in salt. Please?
    1 $pass = "secretpassword";
    2 $hashed = password_hash($pass, PASSWORD_DEFAULT);
    3 echo $hashed;
    Output:
    $2y$10$Q7Rm.Cmcu4lbvI7.C2q4Z.1LLoh4C63vBSfflQtfjs52GxhAc.s/G
    (make your password columns wider! 255 chars recommended)

    View Slide

  17. Easy Password Hashing
    1 $existing_hash = '$2y$10$Q7Rm.Cmcu4lbvI7.C2q4Z.1LLoh4C63vBSfflQt
    2 $pass = "secretpassword";
    3
    4 if(password_verify($pass, $existing_hash))
    5 echo "All good";
    6 else
    7 echo "Go away";
    For PHP < 5.5: http://github.com/ircmaxell/password_compat

    View Slide

  18. Generators (5.5)
    Functions with the ability to emit a sequence of values

    View Slide

  19. Generators
    1 function readLogsFromDatabase() {
    2 $db = new PDO('mysql:host=localhost;dbname=test', $user, $p
    3 $stmt = $db->query("select message from logs");
    4 while ($row = $stmt->fetch()) {
    5 yield $row['message'];
    6 }
    7 }
    8
    9 foreach (readLogsFromDatabase() as $msg) {
    10 echo $msg."\n";
    11 }

    View Slide

  20. Coroutines
    Coroutines are a way of separating interacting concerns
    Generators let us achieve this

    View Slide

  21. Coroutines
    1 function dbLogWriter() {
    2 $db = new PDO('mysql:host=localhost;dbname=test');
    3 $stmt = $db->prepare(
    4 "insert into logs (message) values (:msg);");
    5 while (true) {
    6 $msg = yield;
    7 $stmt->execute(array("msg" => $msg));
    8 }
    9 }

    View Slide

  22. Coroutines
    1 $logger = dbLogWriter();
    2 $logger->send("Hello world!");
    3 $logger->send("Something notable happened");

    View Slide

  23. MySQL Extension is Deprecated (5.5)
    The original mysql extension now emits E_DEPRECATED warnings.
    Instead, use:
    •PDO - excellent OO database handling
    •The mysqli extension, quite similar to the original mysql one

    View Slide

  24. Built-in OpCache (5.5)
    Replaces APC - be aware that OpCache is disabled by default.
    Turn on opcache.enable and opcache.enable_cli

    View Slide

  25. DebugInfo (5.6)
    Magic method __debugInfo() to change what is given to
    var_dump()
    1 class MyBuggyClass {
    2 public function __debugInfo() {
    3 return $this->problemData;
    4 }
    5 }
    6
    7 ...
    8 var_dump(new MyBuggyClass()); // custom output

    View Slide

  26. Variadic Functions (5.6)
    1 function combine($transform, ...$strings) {
    2 $string = '';
    3
    4 foreach($strings as $piece) {
    5 $string .= $piece;
    6 }
    7 return($transform($string));
    8 }
    9
    10 echo combine("strtoupper", "I'd ", "like ", 4 + 2, " apples");
    11 // I'D LIKE 6 APPLES

    View Slide

  27. Argument Unpacking (5.6)
    Let PHP unpack your function parameters
    1 function display_product($name, $id, $price) {} // cool stuffs
    2
    3 $db = new PDO("mysql:host=127.0.0.1;dbname=test");
    4 $sql = "select p.name, p.id, p.price from products p";
    5 $stmt = $db->query($sql);
    6
    7 while(false !== ($prod = $stmt->fetch(PDO::FETCH_NUM))) {
    8 display_product(...$prod);
    9 }

    View Slide

  28. Upgrading An Existing System

    View Slide

  29. Performance Comparison

    View Slide

  30. How To Upgrade
    Turn on E_DEPRECATED and watch the logs of your existing platform
    Set with: error_reporting = E_ALL

    View Slide

  31. How To Upgrade
    Use the PHPCompatibility PHPCS standard
    Install from https://github.com/wimg/PHPCompatibility and
    include in your standards directory

    View Slide

  32. How To Upgrade
    Syntax check your code with new version of PHP
    Use phing (http://www.phing.info/):







    Or try my one-liner: find . -name '*.php' | xargs -n1 php -l

    View Slide

  33. How To Upgrade
    Compile new PHP and run test suite with it
    Run tests: /path/to/php/sapi/cli/php phpunit.phar

    View Slide

  34. How To Upgrade
    Run application with PHP's webserver (5.4+)
    php -S localhost:8080

    View Slide

  35. PHP's Own Webserver
    php -S dev.project.local:8080
    -t /var/www/cool-project/web
    -c php-ini.development
    routing.php

    View Slide

  36. How To Upgrade
    •Turn on E_DEPRECATED and watch the logs of your existing
    platform
    •Use the PHPCompatibility PHPCS standard
    •Lint check with new version (php -l)
    •Compile new PHP and run test suite
    •Run application with PHP's webserver
    •Upgrade a test/staging platform
    •Go for it!

    View Slide

  37. New Platforms
    For new projects, or old ones, platforms must be PHP 5.5+

    View Slide

  38. Questions? (and resources)
    Feedback please! https://m.joind.in/talk/c173e
    Intermediate PHP:
    •http://lrnja.net/php-video
    Contact me:
    •@lornajane
    •http://lornajane.net

    View Slide

  39. Bonus Content

    View Slide

  40. Namespaced Functions (5.6)
    Have always been able to namespace functions
    Can now import them, like classes
    1 include "Lib/Many/Layers/functions.php";
    2 use function \Lib\Many\Layers\deep_func;
    3
    4 deep_func();

    View Slide

  41. Filter Handles MAC Addresses (5.5)
    Stealth feature (it doesn't seem to be documented!)
    1 $mac1 = "12-34-56-78-9A-BC";
    2 var_dump(filter_var($mac1, FILTER_VALIDATE_MAC));
    3 // string(17) "12-34-56-78-9A-BC"
    4
    5 $mac2 = "12-34-567-A-BC";
    6 var_dump(filter_var($mac2, FILTER_VALIDATE_MAC));
    7 // bool(false)

    View Slide

  42. JSON Shininess (5.4)
    JSONSerializable interface defines the data that is included when
    object is passed to json_encode()
    Also very handy additional switches to json_encode():
    •JSON_PRETTY_PRINT
    •JSON_UNESCAPED_SLASHES
    •JSON_UNESCAPED_UNICODE

    View Slide

  43. Reusable php://input (5.6)
    The php://input stream gives access to the incoming request body
    From PHP 5.6, it can be opened multiple times

    View Slide