Eine kleiner Reminder... PHP 5.3 und seine neuen Features. Im Rahmen dieser Veranstaltung konnte bei weitem nicht alles genannt werden, was die neue Version anbietet. Diese Session zeigte an Hand von konkreten Beispielen die Anwendung einiger dieser Features.
PHP Usergroup Rheinhessen,
Session vom 2010-04-06
Back to the future - Plone 5.2 und Python 3 Migration am Beispiel Onkopedia
PHP 5.3 - da war doch was?
1. PHP 5.3
...da war doch was?!
PHP 5.3 | Benjamin Josefus 2010-04-06 1
2. Agenda
● PHP Evolution
● Funktionsstamm
● Sprachkonstrukte
● u.a. Namespaces und Closures
● Late Static Binding
● Migration
PHP 5.3 | Benjamin Josefus 11.04.10 2
3. PHP // Historie
Personal
Home PHP/FI
PHP/FI PHP 3 PHP 4 PHP 5
Page PHP/FI 2
Tools
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 11.04.10 3
4. PHP // Evolution
Personal
Home PHP/FI
PHP/FI PHP 3 PHP 4 PHP 5 PHP 6
Page PHP/FI 2
Tools
1995 1996 1998 2000 2004 PLAN 2006
● PHP 6 initial für 2006 geplant
● Schwierigkeiten mit Kern Features um UTF16
Kodierung und Namespacing
● Verschoben bis <?>...
PHP 5.3 | Benjamin Josefus 11.04.10 4
5. 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 11.04.10 5
6. PHP // Evolution
Personal
Home PHP/FI
PHP/FI PHP 3 PHP 4 PHP 5 PHP 5.3 PHP 6
Page PHP/FI 2
Tools
1995 1996 1998 2000 2004 07/2009 ?
● 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)
PHP 5.3 | Benjamin Josefus 11.04.10 6
7. 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 11.04.10 7
8. Erweiterter Funktionsstamm
● Auswahl...
● Neben ucfirst() jetzt auch lcfirst()
● preg_filter() vereint preg_grep() und preg_replace()
● file_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 11.04.10 8
9. 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 11.04.10 9
10. Neue Sprachkonstrukte
● Jump Label „goto“
● Namespaces
● Konstanten außerhalb Klassen
● Closures
● Late Static Binding
PHP 5.3 | Benjamin Josefus 11.04.10 10
11. Jump Label „goto“
● Sprunganweisung -> gehe zu Label „foo“
<?php <?php
goto foo; foo: {
echo 'Foo'; $i = 0;
while ($i++ < 100)
foo: echo ".";
echo 'Bar'; goto bar;
}
bar: {
goto intermezzo;
● Was macht dieses echo "...und nochmal...";
goto foo;
Programm? => }
intermezzo: {
echo "nun mal ne pause";
sleep(1);
}
PHP 5.3 | Benjamin Josefus 11.04.10 11
12. Jump Label „goto“
● Sprunganweisung -> gehe zu Label „foo“
<?php <?php
goto foo; foo: {
echo 'Foo'; $i = 0;
while ($i++ < 100)
foo: echo ".";
echo 'Bar'; goto bar;
}
bar: {
goto intermezzo;
● Was macht dieses echo "...und nochmal...";
goto foo;
Programm? => }
● Goto-Structs haben intermezzo: {
echo "nun mal ne pause";
keinen Return Value sleep(1);
}
● Sequenzieller Ablauf
● Nicht aus „switch“ anwendbar!
PHP 5.3 | Benjamin Josefus 11.04.10 12
13. 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 11.04.10 13
14. 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 11.04.10 14
15. 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 „“
<?php
require_once 'de/phpugrhh/autoloader/Autoloader.php';
use dephpugrhhautoloaderAutoloader;
Autoloader::autoload();
use SimpleXmlElement;
use dephpugrhhexmapleXmlParser;
$sxe = new SimpleXmlElement('/path/to/file.xml', null, true);
$parser = new XmlParser($sxe);
$parser->parse();
PHP 5.3 | Benjamin Josefus 11.04.10 15
16. Namespace Autoloader
● Autoloader mit __NAMESPACE__ Konstante
<?php
namespace dephpugrhhautoloader;
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'));
}
}
PHP 5.3 | Benjamin Josefus 11.04.10 16
17. Namespaces
● Ein reales Anwendungsbeispiel
<?php
namespace netopencsiserver; /* ... */
use netopencsicsibaseCSIMessageObject; /**
use netopencsicsigenLogindata; * @param CSIMessageObject $message
use netopencsicsigenServiceNewsRss; * CSI stream with CSI data
use netopencsicsigenGeneratedHandler; * @return integer
use netopencsiserversessionSessionInfo; * @see GeneratedHandler::addReceivedMessage()
*/
final class ServerHandler extends GeneratedHandler public function addRcvdMessage(CSIMessageObject
{ $msg)
/** {
* @var ServerController $this->_handleSession($msg->getSessionID());
*/ return parent::addRcvdMessage($msg);
protected $_serverController; }
/**
/** * @param string $sessionId
* @param ServerController $serverController * @return void
*/ */
public function __construct(ServerController $sC) protected function _handleSession($sessId)
{ {
parent::__construct(); SessionInfo::getInstance()->start($sessId);
$this->_serverController = $sC; Auth::authenticate(SessionInfo::getInstance());
} }
/* ... */
/* ... */
}
PHP 5.3 | Benjamin Josefus 11.04.10 17
18. Namespaces
● Kein „use“ für Klassen gleichem Namespace
<?php
namespace netopencsiserver; /* ... */
use netopencsicsibaseCSIMessageObject; /**
use netopencsicsigenLogindata; * @param CSIMessageObject $message
use netopencsicsigenServiceNewsRss; * CSI stream with CSI data
use netopencsicsigenGeneratedHandler; * @return integer
use netopencsiserversessionSessionInfo; * @see GeneratedHandler::addReceivedMessage()
*/
final class ServerHandler extends GeneratedHandler public function addRcvdMessage(CSIMessageObject
{ $msg)
/** {
* @var ServerController $this->_handleSession($msg->getSessionID());
*/ return parent::addRcvdMessage($msg);
protected $_serverController; }
/**
/** * @param string $sessionId
* @param ServerController $serverController * @return void
*/ */
public function __construct(ServerController $sC) protected function _handleSession($sessId)
{ {
parent::__construct(); SessionInfo::getInstance()->start($sessId);
$this->_serverController = $sC; Auth::authenticate(SessionInfo::getInstan
} }
/* ... */
/* ... */
PHP 5.3 | Benjamin Josefus }
11.04.10 18
19. Konstanten außerhalb Klassen
<?php
const 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: Ausgabe PHP >= 5.3:
Parse error: syntax error, unexpected T_CONST in Case ONE
/media/laptop/workspace-phpug/php5.3/constants/
constants.php on line 2
PHP 5.3 | Benjamin Josefus 11.04.10 19
20. Konstanten außerhalb Klassen
● Früher gab es globale Konstanten
<?php
define ('PHPUG_ONE', 1);
...
● Heute können sie namensraumbasiert sein
<?php
namespace dephpugrhhconstants;
define ('PHPUG_ONE', 1); // global
const PHPUG_TWO = 2; // namespaced in dephpugrhhconstants
<?php
namespace dephpugrhhuseconst;
require_once 'constants.php';
var_dump(PHPUG_ONE);
var_dump(PHPUG_TWO); // <--- Notice: Use of undefined constant PHPUG_TWO
var_dump(dephpugrhhconstantsPHPUG_TWO);
PHP 5.3 | Benjamin Josefus 11.04.10 20
21. 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 11.04.10 21
22. Closures
● Beispiel einfache „Addiermaschine“
<?php
function adder($x) {
return function ($y) use ($x) {
return $x + $y;
};
}
$closure = adder(10);
echo $closure(5); // outputs 15
echo $closure(15); // outputs 25
echo $closure(25); // outputs 35
PHP 5.3 | Benjamin Josefus 11.04.10 22
23. Closures
Rückgabe einer
anonymen Funktion
● Beispiel einfache „Addiermaschine“
<?php
function adder($x) {
return function ($y) use ($x) {
return $x + $y;
};
}
„Freie Variable im
$closure = adder(10); eigenen Kontext“
echo $closure(5); // outputs 15
echo $closure(15); // outputs 25
10 bleibt
echo $closure(25); im outputs 35
//
Kontext erhalten
PHP 5.3 | Benjamin Josefus 11.04.10 23
24. Closures
● Komplexes Anwendungsbeispiel: „Synchronizer“
● Callback Function kapselt shared Object
namespace jfootexperimentalconcurrentsync;
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 11.04.10 24
25. Closures
● Anwenden des Synchronizers
namespace jfootexperimentalconcurrentsync;
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 11.04.10 25
26. Late Static Binding
● Statische Member und Funktionen
● „self“ greift auf Basis Klasse! Auch bei PHP5.3
● Keine Instanz! Auflösung zur „Translate-Zeit“
<?php
class Foo
{
protected static $_member = 2;
public static function getStaticMember()
{
return self::$_member;
}
}
<?php <?php
class Bar extends Foo
{ var_dump(Bar::getStaticMember());
protected static $_member = 7; // outputs 2!
}
PHP 5.3 | Benjamin Josefus 11.04.10 26
27. Late Static Binding
● Neben „self“ gibt es nun auch „static“
● Erzwingt späte Auflösung zur Laufzeit
<?php
class Foo
{
protected static $_member = 2;
public static function getStaticMember()
{
return static::$_member;
}
}
<?php <?php
class Bar extends Foo
{ var_dump(Bar::getStaticMember());
protected static $_member = 7; // outputs 7!
}
PHP 5.3 | Benjamin Josefus 11.04.10 27
28. Late Static Binding
● Neben __call() auch __callStatic() als
Magic Method
● Spätes Auflösen des Klassennamens einer
Instanz mittels get_called_class()
<?php
class Foo
{
public function __callStatic($name, $params)
{
var_dump(get_called_class());
var_dump($name, $params);
}
}
<?php
Foo::callPseudoFunc(123);
// outputs 'Foo'
// outputs 'callPseudoFunc' and 123
PHP 5.3 | Benjamin Josefus 11.04.10 28
29. Ein paar Migrationshinweise
● Neue Laufzeitfehler
● E_DEPRECATED
● Deprecated (ab PHP 6 weg)
● register_globals
● safe_mode
● magic_quotes_gpc
PHP 5.3 | Benjamin Josefus 11.04.10 29
30. 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 11.04.10 30
31. 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 11.04.10 31
32. Das war's!
● Vielen Dank für die Aufmerksamkeit!
● Fragen? Anregungen? Diskussionsbedarf?
Benjamin Josefus
Dipl.-Inform. (FH)
Zend Certified Engineer
Kontakt:
benjamin@josefus.net
twitter.com/bensh_
PHP 5.3 | Benjamin Josefus 11.04.10 32