• No results found

The PHP 5.4 Features You Will Actually Use

N/A
N/A
Protected

Academic year: 2021

Share "The PHP 5.4 Features You Will Actually Use"

Copied!
54
0
0

Loading.... (view fulltext now)

Full text

(1)

The PHP 5.4 Features You Will

Actually Use

(2)

About Me

• Lorna Jane Mitchell

• PHP Consultant/Developer

• Author of PHP Master (Sitepoint) and PHP Web Services (O’Reilly) • Twitter: @lornajane

(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*

(4)
(5)
(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');

(8)

Array Syntax

Now we can do:

$game = ['scissors', 'stone', 'paper'];

print_r($game);

$game = [0 => 'scissors', 1 => 'stone', 2 => 'paper'];

(9)
(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];

(11)
(12)
(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

(14)
(15)
(16)
(17)
(18)
(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)

Trait Example From ZF2

namespace Zend\EventManager; trait ProvidesEvents

{

public function setEventManager(EventManagerInterface $events) {

$identifiers = array(__CLASS__, get_called_class()); $events->setIdentifiers($identifiers);

$this->events = $events;

return $this; }

public function getEventManager() {

if (!$this->events instanceof EventManagerInterface) { $this->setEventManager(new EventManager());

}

return $this->events; }

(21)

Using Traits

Apply it like this: class Magic {

use \Zend\EventManager\ProvidesEvents;

// more magical things

}

$magic = new Magic();

(22)

Other Trait Trivia

(23)

Other Trait Trivia

• They can be aliased when used

(24)

Other Trait Trivia

• They can be aliased when used

• There are rules about resolving naming clashes • Traits can include properties

(25)

Other Trait Trivia

• They can be aliased when used

• There are rules about resolving naming clashes • Traits can include properties

(26)

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

(27)
(28)

Built In Webserver

Built in application server for PHP 5.4

• Simple

• Lightweight

• Development use only

From the manual: "Requests are served sequentially."

(29)

Webserver Examples

Start a simple server on a port number of your choice

php -S localhost:8080

(30)

Webserver Examples

Change the hostname:

php -S dev.project.local:8080

(31)

Webserver Examples

Specify the docroot

php -S localhost:8080 -t /var/www/superproject

Specify which php.ini to use (default: none)

(32)

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

(33)
(34)

Session Upload Progress

File upload progress, written to the session at intervals

(35)

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" />

(36)

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) { ... } } } }

(37)

Anonymous Functions, __invoke and

the Callable Typehint

(38)

Typehinting

We can typehint in PHP, on:

• Classes

• Interfaces

(39)

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

(40)

Anonymous Functions

• Literally functions with no name

• More convenient than create_function()

Example:

$ping = function() {

echo "ping!"; };

(41)

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

(42)

Callable Examples

function sparkles(Callable $func) { $func();

return "fairy dust"; }

class Butterfly {

public function __invoke() {

echo "flutter"; }

}

$bee = new Butterfly();

(43)
(44)

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

(45)

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()

(46)

JsonSerializable Example

class gardenObject implements JsonSerializable {

public function jsonSerialize() { $data[] = $this->flowers;

$data[] = $this->fruit;

return $data; }

}

$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);

(47)
(48)

Removed Features

• register_globals • register_long_arrays • safe_mode • magic_quotes • allow_call_time_pass_reference • y2k_compliance

(49)

Upgrading to PHP 5.4

• Turn on E_DEPRECATED in PHP 5.3

• Warns when you use features which are gone in 5.4

(50)
(51)
(52)

The PHP 5.4 Features I’ll Actually Use

• Short array syntax • Traits

• Built in webserver • Upload progress • Callable

(53)
(54)

Thanks!

Resources all here: http://lrnja.net/KOouXv

Twitter: @lornajane

References

Related documents

(2007) noted that post-disaster reconstruction is quite similar to that of low-cost community housing projects in developing countries, but with added challenges.

For example, prediction with an observed graph, G , is inherently transductive since unlabeled data influence the topology of the graph ( Culp and Michailidis 2008a ); or in cases

Two studies demonstrated that actors’ perceived knowledge about interaction partners (APK) relative to their perceptions of their partners’ knowledge gained about the self (APPK)

Stenting of the common bile duct can provide palliation of biliary obstruction, through the use of temporary stents in patients who will undergo surgery or with permanent stents

Such a collegiate cul- ture, like honors cultures everywhere, is best achieved by open and trusting relationships of the students with each other and the instructor, discussions

Building on previous work, and using household survey data and the Own-Child reverse-survival method, the paper presents for the first time total fertility and age-specific

Als we de voorgaande hoofdstukken goed hebben bestudeerd en door veel oefenen de nodige vaardigheid hebben gekregen, moeten we nu in staat zijn, een vakkundige tekening te maken.

From inception through build-out, our award-winning work on the original 107-mile network and key extensions has encompassed the full range of engineering services,