PHP 5.3 - da war doch was?

32
PHP 5.3 | Benjamin Josefus 1 2010-04-06 PHP 5.3 ...da war doch was?!

Transcript of PHP 5.3 - da war doch was?

PHP 5.3 | Benjamin Josefus 12010-04-06

PHP 5.3...da war doch was?!

PHP 5.3 | Benjamin Josefus 211.04.10

Agenda

● PHP Evolution● Funktionsstamm● Sprachkonstrukte

● u.a. Namespaces und Closures

● Late Static Binding● Migration

PHP 5.3 | Benjamin Josefus 311.04.10

PHP // Historie

PersonalHomePageTools

PHP/FI PHP 3 PHP/FI

PHP/FI 2 PHP 4 PHP 3 PHP 5

1995 1996 1998 2000 2004

● Sammlung von Perl Skripten zur Website Auswertung-

● PHP FI („Form Interpreter“)

● PHP3 Implementierung in C „PHP Hypertext Preprocessor“

● PHP4 mit „Zend Engine“ (Compiler und VM), ab PHP 5 ausgereifte OO Möglichkeiten-

PHP 5.3 | Benjamin Josefus 411.04.10

PHP // Evolution

PersonalHomePageTools

PHP/FI PHP 3 PHP/FI

PHP/FI 2 PHP 4 PHP 3 PHP 5 PHP 6

● PHP 6 initial für 2006 geplant● Schwierigkeiten mit Kern Features um UTF16

Kodierung und Namespacing● Verschoben bis <?>...

1995 1996 1998 2000 2004 PLAN 2006

PHP 5.3 | Benjamin Josefus 511.04.10

PHP 6?

● PHP 6 bereits seit 2004 in der Entwicklung● Lange Diskussionen, kein Entscheidungsdrang● Hauptproblem Kern Neuerung um Unicode- -

Unterstützung● Auch immer noch einige andere TODOs

● http://wiki.php.net/todo/php60

● Backport von (den meisten) PHP 6 Features in den 5er Branch-

PHP 5.3 | Benjamin Josefus 611.04.10

PHP // Evolution

PersonalHomePageTools

PHP/FI PHP 3 PHP/FI

PHP/FI 2 PHP 4 PHP 3 PHP 5 PHP 6 PHP 5.3

● Backport der meisten PHP 6 Features nach PHP 5.3

● Was lange währt, wird endlich gut!

● PHP 6 Release Date immer noch nicht sicher

● PHP 5.4 Branch eröffnet... (März 2010)

1995 1996 1998 2000 2004 07/2009 ?

PHP 5.3 | Benjamin Josefus 711.04.10

Und, was gibt’s Neues?

● Verbesserte Windows Unterstützung-● Neue Funktionen, Sprachkonstrukte

● Native DB Unterstützung-● mysqlnd (Achtung: Inkompatibel zu MySQL < 4.1)● SQLite3 (Achtung: Inkompatibel zu SQLite2!)

● Verbessertes Objektmodell● Performantes Auflösen von Zirkelbezügen

● Erweiterungen in SPL

● Performance, Performance, Performance

PHP 5.3 | Benjamin Josefus 811.04.10

Erweiterter Funktionsstamm

● Auswahl...● Neben ucfirst() jetzt auch lcfirst()● preg_filter() vereint preg_grep() und preg_replace()● f i le_get_contents() kann nun auch POST Requests

absetzen (? curl mit CURLOPT_POST!)→● strstr() kann nun incl. und excl. $needle strippen● fgetcsv() kann nun escapen● round() kann auf und abrunden-● nl2br() kann neben XHTML <br/> auch <br> erzeugen● ...

PHP 5.3 | Benjamin Josefus 911.04.10

Navtive MySQL Unterstützung

● MySQL Native Driver „mysqlnd“● Neben ext/mysql, ext/mysqli, PDO_MYSQL● Nach dev.mysql.com Ersatz für MySQL Client

„libmysql“ *

● Kommt mit einigen Performanceschüben● Nutzt Zend Engine Speichermanagement● Nicht über my.cnf konfiguriert!● Inkompatibel zu MySQL < 4.1* http://dev.mysql.com/downloads/connector/php-mysqlnd/

PHP 5.3 | Benjamin Josefus 1011.04.10

Neue Sprachkonstrukte

● Jump Label „goto“● Namespaces● Konstanten außerhalb Klassen● Closures● Late Static Binding

PHP 5.3 | Benjamin Josefus 1111.04.10

Jump Label „goto“

● Sprunganweisung > gehe zu Label „foo“-

● Was macht dieses Programm? =>

<?phpgoto foo;echo 'Foo'; foo:echo 'Bar';

<?phpfoo: { $i = 0; while ($i++ < 100) echo "."; goto bar;}

bar: { goto intermezzo; echo "...und nochmal..."; goto foo;}

intermezzo: { echo "nun mal ne pause"; sleep(1);}

PHP 5.3 | Benjamin Josefus 1211.04.10

Jump Label „goto“

● Sprunganweisung > gehe zu Label „foo“-

● Was macht dieses Programm? =>

● Goto Structs haben - keinen Return Value

● Sequenzieller Ablauf● Nicht aus „switch“ anwendbar!

<?phpgoto foo;echo 'Foo'; foo:echo 'Bar';

<?phpfoo: { $i = 0; while ($i++ < 100) echo "."; goto bar;}

bar: { goto intermezzo; echo "...und nochmal..."; goto foo;}

intermezzo: { echo "nun mal ne pause"; sleep(1);}

PHP 5.3 | Benjamin Josefus 1311.04.10

Namespaces

● Namespaces kapseln Code und vermeiden Kollisionen

● Beispiel: Dateisystem ● /home/ben/file.txt● /var/www/file.txt

● Konkret: Paketierung von Programmcode● Wiederverwendbarkeit, Schaffung von

Bibliotheken

PHP 5.3 | Benjamin Josefus 1411.04.10

Namespaces

● Korrellation Dateisystem und Klassenpfad

● Beispiel ZF PDO_MySQL Adapter● Zend/Db/Adapter/Pdo/Mysql.php

● Zend_Db_Adapter_Pdo_Mysql

● Kann je nach Verzeichnistiefe sehr lang werden● Zend_Search_Lucene_Analysis_Analyzer_Common_Text_CaseInsensitive

● Deklarieren mit „namespace“

● Benutzen mit „use“● Lediglich eine Absichtserklärung● Autom. Einbinden einer Namespace Klasse mittels - __autoload()

(oder SPL Variante) [bekannt]

PHP 5.3 | Benjamin Josefus 1511.04.10

Namespaces

● Nach autoload() wird per Lazy Loading instatiiert

● „use“ (PHP) kein „import“ (JAVA) ● „use“ hat hier nur hinweisenden Charakter!● Standard Klassen haben unterliegen dem Root-

Namespace „\“<?phprequire_once 'de/phpugrhh/autoloader/Autoloader.php';use de\phpugrhh\autoloader\Autoloader;

Autoloader::autoload();

use \SimpleXmlElement; use de\phpugrhh\exmaple\XmlParser;

$sxe = new SimpleXmlElement('/path/to/file.xml', null, true);$parser = new XmlParser($sxe);$parser->parse();

PHP 5.3 | Benjamin Josefus 1611.04.10

Namespace Autoloader

<?phpnamespace de\phpugrhh\autoloader;

final class Autoloader{ public static function autoload($name) { $dirname = __DIR__; $namespaceDir = str_replace('\\', DIRECTORY_SEPARATOR, __NAMESPACE__); $loadingDir = substr($dirname, 0, strpos($dirname, $namespaceDir)); $fileName = str_replace('\\', DIRECTORY_SEPARATOR, $name) . '.php'; $file = $loadingDir . DIRECTORY_SEPARATOR . $fileName; if (is_readable($file)) { require_once $file; } } public static function register() { spl_autoload_register(array(__CLASS__, 'autoload')); }}

● Autoloader mit __NAMESPACE__ Konstante

PHP 5.3 | Benjamin Josefus 1711.04.10

Namespaces

<?phpnamespace net\opencsi\server;

use net\opencsi\csi\base\CSIMessageObject;use net\opencsi\csi\gen\Logindata;use net\opencsi\csi\gen\ServiceNewsRss;use net\opencsi\csi\gen\GeneratedHandler;use net\opencsi\server\session\SessionInfo;

final class ServerHandler extends GeneratedHandler{ /** * @var ServerController */ protected $_serverController;

/** * @param ServerController $serverController */ public function __construct(ServerController $sC) { parent::__construct(); $this->_serverController = $sC; } /* ... */

/* ... */

/** * @param CSIMessageObject $message * CSI stream with CSI data * @return integer * @see GeneratedHandler::addReceivedMessage() */ public function addRcvdMessage(CSIMessageObject

$msg) { $this->_handleSession($msg->getSessionID()); return parent::addRcvdMessage($msg); }

/** * @param string $sessionId * @return void */ protected function _handleSession($sessId) { SessionInfo::getInstance()->start($sessId); Auth::authenticate(SessionInfo::getInstance()); }

/* ... */ }

● Ein reales Anwendungsbeispiel

PHP 5.3 | Benjamin Josefus 1811.04.10

Namespaces

● Kein „use“ für Klassen gleichem Namespace<?phpnamespace net\opencsi\server;

use net\opencsi\csi\base\CSIMessageObject;use net\opencsi\csi\gen\Logindata;use net\opencsi\csi\gen\ServiceNewsRss;use net\opencsi\csi\gen\GeneratedHandler;use net\opencsi\server\session\SessionInfo;

final class ServerHandler extends GeneratedHandler{ /** * @var ServerController */ protected $_serverController;

/** * @param ServerController $serverController */ public function __construct(ServerController $sC) { parent::__construct(); $this->_serverController = $sC; } /* ... */

/* ... */

/** * @param CSIMessageObject $message * CSI stream with CSI data * @return integer * @see GeneratedHandler::addReceivedMessage() */ public function addRcvdMessage(CSIMessageObject

$msg) { $this->_handleSession($msg->getSessionID()); return parent::addRcvdMessage($msg); }

/** * @param string $sessionId * @return void */ protected function _handleSession($sessId) { SessionInfo::getInstance()->start($sessId); Auth::authenticate(SessionInfo::getInstance()); }

/* ... */ }

PHP 5.3 | Benjamin Josefus 1911.04.10

Konstanten außerhalb Klassen<?phpconst PHPUG_ONE = 1;const PHPUG_TWO = 2;

$param = PHPUG_ONE;

$outStream = fopen('php://stdout', 'r+');

switch ($param) { case PHPUG_ONE: fwrite($outStream, 'Case ONE' . PHP_EOL); break; case PHPUG_TWO: fwrite($outStream, 'Case TWO' . PHP_EOL); break; default: fwrite($outStream, 'Default Case' . PHP_EOL);}

fclose($outStream);

Ausgabe PHP < 5.3:Parse error: syntax error, unexpected T_CONST in /media/laptop/workspace-phpug/php5.3/constants/constants.php on line 2

Ausgabe PHP >= 5.3:Case ONE

PHP 5.3 | Benjamin Josefus 2011.04.10

Konstanten außerhalb Klassen

<?phpdefine ('PHPUG_ONE', 1);...

● Früher gab es globale Konstanten

● Heute können sie namensraumbasiert sein

<?phpnamespace de\phpugrhh\useconst;

require_once 'constants.php';

var_dump(PHPUG_ONE);var_dump(PHPUG_TWO); // <--- Notice: Use of undefined constant PHPUG_TWO var_dump(\de\phpugrhh\constants\PHPUG_TWO);

<?phpnamespace de\phpugrhh\constants;

define ('PHPUG_ONE', 1); // globalconst PHPUG_TWO = 2; // namespaced in de\phpugrhh\constants

PHP 5.3 | Benjamin Josefus 2111.04.10

Closures

● Früher: create_function()● Anonyme Funktionen ohne Namensbindung● Möglichkeit der funktionalen Programmierung

(Lambda Funktionen)● Erstellung erst zur Laufzeit ● Nutzt freie Variablen im eigenen lexikalischen

Kontext● Nachfolgend einige Beispiele...

PHP 5.3 | Benjamin Josefus 2211.04.10

Closures

<?phpfunction adder($x) { return function ($y) use ($x) { return $x + $y; };}$closure = adder(10);

echo $closure(5); // outputs 15echo $closure(15); // outputs 25echo $closure(25); // outputs 35

● Beispiel einfache „Addiermaschine“

PHP 5.3 | Benjamin Josefus 2311.04.10

Closures

<?phpfunction adder($x) { return function ($y) use ($x) { return $x + $y; };}$closure = adder(10);

echo $closure(5); // outputs 15echo $closure(15); // outputs 25echo $closure(25); // outputs 35

● Beispiel einfache „Addiermaschine“

„Freie Variable im eigenen Kontext“

Rückgabe einer anonymen Funktion

10 bleibt im Kontext erhalten

PHP 5.3 | Benjamin Josefus 2411.04.10

Closures

● Komplexes Anwendungsbeispiel: „Synchronizer“● Callback Function kapselt shared Object

namespace jfoot\experimental\concurrent\sync;final class Synchronizer{ public static function synchronized(Syncable $syncableObject, $callbackFunction) { if (!is_callable($callbackFunction)) { throw new SyncException(/* ... */); } self::wait($syncableObject);

// call closure callback function $callbackFunction($syncableObject); self::signal($syncableObject); } /* ... */}

PHP 5.3 | Benjamin Josefus 2511.04.10

Closures

● Anwenden des Synchronizersnamespace jfoot\experimental\concurrent\sync;class AnyTask extends Task { protected $_syncObject; public function __construct(Syncable $sync) { parent::__construct(); $this->_syncObject = $sync; }

protected function run() { $i = 0; while ($i++ < 100) { Synchronizer::synchronized($this->_syncObject, function(Syncable $s) use ($i) {

$s->write($i); } ); // end synchronized } }}

PHP 5.3 | Benjamin Josefus 2611.04.10

<?phpclass Foo { protected static $_member = 2;

public static function getStaticMember() { return self::$_member; }}

Late Static Binding

● Statische Member und Funktionen ● „self“ greift auf Basis Klasse! Auch bei PHP5.3● Keine Instanz! Auflösung zur „Translate Zeit“-

<?phpclass Bar extends Foo { protected static $_member = 7;}

<?php

var_dump(Bar::getStaticMember());// outputs 2!

PHP 5.3 | Benjamin Josefus 2711.04.10

<?phpclass Foo { protected static $_member = 2;

public static function getStaticMember() { return static::$_member; }}

Late Static Binding

● Neben „self“ gibt es nun auch „static“● Erzwingt späte Auflösung zur Laufzeit

<?phpclass Bar extends Foo { protected static $_member = 7;}

<?php

var_dump(Bar::getStaticMember());// outputs 7!

PHP 5.3 | Benjamin Josefus 2811.04.10

Late Static Binding

● Neben __call() auch __callStatic() als Magic Method

● Spätes Auflösen des Klassennamens einer Instanz mittels get_called_class()<?phpclass Foo { public function __callStatic($name, $params) { var_dump(get_called_class()); var_dump($name, $params); }}

<?phpFoo::callPseudoFunc(123);// outputs 'Foo'// outputs 'callPseudoFunc' and 123

PHP 5.3 | Benjamin Josefus 2911.04.10

Ein paar Migrationshinweise

● Neue Laufzeitfehler ● E_DEPRECATED

● Deprecated (ab PHP 6 weg)● register_globals● safe_mode● magic_quotes_gpc

PHP 5.3 | Benjamin Josefus 3011.04.10

Ein paar Migrationshinweise

● Magic Methods MÜSSEN public sein● Reserviertes Keyword „goto“● In /OutStreaming über - fopen() nur noch mit

Angabe eines Streamwrapper Protokolls (http, -file, zlib,...)

● php_pdo_oci8.dll bei Windows nicht weiter unterstützt

PHP 5.3 | Benjamin Josefus 3111.04.10

Ein paar Migrationshinweise

● ALLE ereg Funktionen sind DEPRECATED-<?php$string = 'PHP,UG,Rheinhessen';

// php 5.3 raises "Deprecated Warning"var_dump(split(',', $string));

// php 5.3 raises "Deprecated Warning"var_dump(ereg(',', $string));

PHP 5.3 | Benjamin Josefus 3211.04.10

Das war's!

● Vielen Dank für die Aufmerksamkeit!● Fragen? Anregungen? Diskussionsbedarf?

Benjamin JosefusDipl.-Inform. (FH)Zend Certified Engineer

Kontakt:[email protected] twitter.com/bensh_