Grouping objects Collections and iterators. Main concepts to be covered Collections Loops Iterators.
PHP 5 to PHP 6talks.somabo.de/200702_mexico_consol.pdf · 2007-03-14 · Marcus Börger PHP Wrap-Up...
Transcript of PHP 5 to PHP 6talks.somabo.de/200702_mexico_consol.pdf · 2007-03-14 · Marcus Börger PHP Wrap-Up...
PHP Wrap-up
Marcus Börger
Mexico CONSOL 2007
Marcus Börger PHP Wrap-Up 2
WelcomeSome statistics
Revisiting PHP 4
Looking at PHP 5.0, 5.1
Upgrading to new PHP 5.2
A glimpse at the future PHP 6
Marcus Börger PHP Wrap-Up 3
PHP usage by IP
Other35%
PHP65%
Nexen Services http://www.nexen.net © 2005 -2007
Marcus Börger PHP Wrap-Up 4
Marcus Börger PHP Wrap-Up 5
27 Dec 2002: PHP 4.3Do not use
InsecureUnsupportedNo longer continued
Marcus Börger PHP Wrap-Up 6
11 Jul 2005: PHP 4.4Fixes a memory corruption with referencesOnly security fixesNo new features at allAvailable for quite some timePHP 4.4.5 released 14th February 2007
No PHP 4.5 will come out
Marcus Börger PHP Wrap-Up 7
PHP 4 and OOP ?Poor Object model
MethodsNo visibilityNo abstracts, No finalStatic without declaration
PropertiesNo static propertiesNo constants
InheritanceNo abstract, final inheritance, no interfacesNo prototype checking, no types
Object handlingCopied by valueNo destructors
Marcus Börger PHP Wrap-Up 8
13 Jul 2004: PHP 5.0Completely rewritten Zend Engine 2.0First version with the new object modelLibxml2 based XML replaces SablotronNew extensions
DOM, MySQLi, PDO, SimpleXML, SPL
Unbundled mysql client library
Sometimes called the "alpha" versionDiscontinued
Marcus Börger PHP Wrap-Up 9
Objects referenced by ID
Objects are no longer somewhat special arraysObjects are no longer copied by defaultObjects may be copied using clone/__clone()
class Object {};
$obj = new Object();
$ref = $obj;
$dup = clone $obj; Class Object
$obj $ref $dup
Instance 1 Instance 2
Marcus Börger PHP Wrap-Up 10
ZE2's revamped object modelObjects are referenced by identifiersConstructors and DestructorsStatic membersDefault property valuesConstantsVisibilityInterfacesFinal and abstract membersInterceptorsExceptionsReflection APIIterators
Marcus Börger PHP Wrap-Up 11
Revamped Object ModelPHP 5 has really good OOP support
Better code reuseBetter for team developmentEasier to refactorSome patterns lead to much more efficient codeFits better in marketing scenarios
Marcus Börger PHP Wrap-Up 12
From engine overloading . . .Zend engine 2.0+ allows to overload the following
by implementing interfacesForeach by implementing Iterator, IteratorAggregateArray access by implementing ArrayAccessSerializing by implementing Serializable
by providing magic functionsFunction invocation by method __call()Property access by methods __get() and __set()Automatic loading of classes by function __autoload()
Marcus Börger PHP Wrap-Up 13
. . . to SPL
It is easy in a complex way- Lukas Smith
php conference 2004
A collection of standard interfaces and classesMost of which based around engine overloading
A few helper functions
Marcus Börger PHP Wrap-Up 14
What is SPL about & what forCaptures some common patterns
Advanced Iterators
Functional programming
File and directory handling
Makes __autoload() useable
Exception hierarchy with documented semantics
Captures some common patterns
Advanced Iterators
Functional programming
File and directory handling
Makes __autoload() useable
Exception hierarchy with documented semantics
Marcus Börger PHP Wrap-Up 15
ExceptionsRespect these rules
1. Exceptions are exceptions2. Never use exceptions for control flow3. Never ever use exceptions for parameter passing
<?phptry {
// your codethrow new Exception();
}catch (Exception $e) {
// exception handling}?>
Marcus Börger PHP Wrap-Up 16
Practical use of exceptionsConstructor failure
Converting errors/warnings to exceptions
Simplify error handling
Provide additional error information by tagging
Marcus Börger PHP Wrap-Up 17
Constructor failureIn PHP 4.4 you would simply unset($this)Provide a param that receives the error condition
<?phpclass Object{
function __construct( & $failure){
$failure = true;}
}$error = false;$o = new Object($error);if (!$error) {
// error handling, NOTE: the object was constructedunset($o);
}?>
Marcus Börger PHP Wrap-Up 18
Constructor failureIn 5 constructors do not return the created objectExceptions allow to handle failed constructors
<?phpclass Object{
function __construct(){
throw new Exception;}
}try {
$o = new Object;}catch (Exception $e) {
echo "Object could not be instantiated\n";}?>
Marcus Börger PHP Wrap-Up 19
Simplify error handlingTypical database access code contains lots of if's
<html><body><?php$ok = false;$db = new PDO('CONNECTION');if ($db) {
$res = $db->query('SELECT data');if ($res) {
$res2 = $db->query('SELECT other');if ($res2) {
// handle data$ok = true; // only if all went ok
}}
}if ($ok) echo '<h1>Service currently unabvailable</h1>';?></body></html>
Marcus Börger PHP Wrap-Up 20
Simplify error handlingTrade code simplicity with a new complexity
<html><body><?phptry {
$db = new PDO('CONNECTION');$db->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);$res = $db->query('SELECT data');$res2 = $db->query('SELECT other');// handle data
}catch (Exception $e) {
echo '<h1>Service currently unabvailable</h1>';error_log($e->getMessage());
}?></body></html>
Marcus Börger PHP Wrap-Up 21
What are IteratorsIterators are a concept to iterate anything that contains other things.
Iterators allow to encapsulate algorithms
Marcus Börger PHP Wrap-Up 22
What are IteratorsIterators are a concept to iterate anything that contains other things. Examples:
Values and Keys in an array ArrayObject, ArrayIteratorText lines in a file SplFileObject
Files in a directory [Recursive]DirectoryIteratorXML Elements or Attributes ext: SimpleXML, DOMDatabase query results ext: PDO, SQLite, MySQLiDates in a calendar range PECL/date (?)Bits in an image ?
Iterators allow to encapsulate algorithms
Marcus Börger PHP Wrap-Up 23
What are IteratorsIterators are a concept to iterate anything that contains other things. Examples:
Values and Keys in an array ArrayObject, ArrayIteratorText lines in a file SplFileObject
Files in a directory [Recursive]DirectoryIteratorXML Elements or Attributes ext: SimpleXML, DOMDatabase query results ext: PDO, SQLite, MySQLiDates in a calendar range PECL/date (?)Bits in an image ?
Iterators allow to encapsulate algorithmsClasses and Interfaces provided by SPL:AppendIterator, CachingIterator, LimitIterator, FilterIterator, EmptyIterator, InfiniteIterator, NoRewindIterator, OuterIterator, ParentIterator, RecursiveIterator, RecursiveIteratorIterator, SeekableIterator, SplFileObject, . . .
Marcus Börger PHP Wrap-Up 24
Array vs. IteratorAn array in PHP $ar = array()
can be rewound: reset($ar)
is valid unless it's key is NULL: !is_null(key($ar))
have current values: current($ar)
have keys: key($ar)
can be forwarded: next($ar)
Something that is traversable $it = new Iterator;
may know how to be rewound: $it->rewind()(does not return the element)
should know if there is a value: $it->valid()
may have a current value: $it->current()
may have a key: $it->key()(may return NULL at any time)
can forward to its next element: $it->next()
Marcus Börger PHP Wrap-Up 25
24 Nov 2005: PHP 5.1New extension XMLReaderAdded new date/time handlingAdd streams filters bz2 and zlibImproved interactive mode php –aMajor changes/improvements to MySQLi and SPLSince 5.1.6 var is an alias for public
Sometimes called 'beta' versionDiscontinued
Marcus Börger PHP Wrap-Up 26
02 Nov 2006: PHP 5.2Current stable version5.2.1 released on 9th February5.2.2+ only small feature changes and additionsImproved the Zend Memory ManagerOver 300 fixes between 5.1.6 and 5.2.1
Marcus Börger PHP Wrap-Up 27
PHP 5.2: New extensionsFilter Input filtering/validation
Date Date handling functions and objects
JSON JavaScript Object Notation
XMLWriter Counterpart to XMLReader
ZIP Full read & write ZIP support
Marcus Börger PHP Wrap-Up 28
PHP 5.2: New featuresNow __tostring() works as expected everywhereNew error severity E_RECOVERABLE_ERRORAdded/improved SPL features
RegexIteratorSplFileObject with CSV read supportCachingIterator now allows caching
RFC 2397 (data: stream) supportAdded forward support for 'b' prefix to stringsLots of minor additions/improvements
Marcus Börger PHP Wrap-Up 29
PHP 5.2: PerformanceNew Memory Manager + Heap ProtectionFaster include/require_onceOptimized str_replace() and implode() functionsFaster try {} catch {} blocksSignificantly faster performance on Win32Optimized shutdown sequenceMany other optimizations
Marcus Börger PHP Wrap-Up 30
PHP 5.2: SecurityNew configuration option allow_url_includeOver 40 security fixesMore accurate memory usage trackingFilter extension can help filter out hostile input
XSSSQL Injection
Memory limit is always enabled.
Marcus Börger PHP Wrap-Up 31
PHP 5.2: ChangesRespect new E_RECOVERABLE_ERROR in E_ALLNo more 'abstract static' methods in classesWhen using external resources, allow_url_includeFinally activated classes DateTime, DateTimeZoneInheritance rules check for return by reference
Detailed instructions in README.UPDATE_5_2
Marcus Börger PHP Wrap-Up 32
PHP 5.3Scheduled for end of 2007New features that cannot be done in 5.2
In discussion:Bundling APC or another compiler cacheNamespacesAdding operator ifsetor or ?:
$a = ifsetor($input, $default);
$a = $input ?: $default;
Marcus Börger PHP Wrap-Up 33
PHP 6Integrated native Unicode support leveraging ICUExtensions iconv and mbstring get deprecated
Native Unicode string type using UTF-16Additional binary string typeBackwards compatibleControlled via INI --unicode-semantics={on|off}New escape sequences \uXXXX and \UXXXXXXXX
Marcus Börger PHP Wrap-Up 34
--unicode.semantics=offOld behavior where 1 character means 1 byte
$str = "Hello, world"; // ASCII encodingecho strlen($str); // result is 12
$jp = "検索オプション"; // UTF-8 encodingecho strlen($jp); // result is 21
Marcus Börger PHP Wrap-Up 35
--unicode.semantics=onStrings are unicode type; 1 character >= 1 byte
$str = "Hello, world"; // Unicode stringecho strlen($str); // result is 12
$jp = "検索オプション"; // Unicode stringecho strlen($jp); // result is 7
Marcus Börger PHP Wrap-Up 36
Wait, I like binaryThe prefix b denotes binary literals
$str = b"Hello, world"; // Binary stringecho strlen($str); // result is 12
Marcus Börger PHP Wrap-Up 37
At Last some HintsList of all SPL classes PHP 5.0.0
php –r 'print_r(array_keys(spl_classes()));'
Reflection of a built-in class PHP 5.1.2php --rc <Class>
Reflection of a function or method PHP 5.1.2php --rf <Function>
Reflection of a loaded extension PHP 5.1.2php --re <Extension>
Extension information/configuration PHP 5.2.2php --ri <Extension>
Marcus Börger PHP Wrap-Up 38
THANK YOUThis Presentation
http://somabo.de/talks/PHP
http://php.netUpgrading to 5.2
README.UPDATE_5_2SPL Documentation
http://php.net/~hellyPhar
http://pecl.php.net/packages/pharhttp://php.net/phar