Upload
michelangelo-van-dam
View
4.366
Download
0
Embed Size (px)
Citation preview
SPL, not a bridge too farDutch PHP Conference 2009 - Amsterdam
Who am I ?
2
Michelangelo van DamIndependent Enterprise PHP consultant
@dragonbe
http://dragonbe.com
Who are you ?
You know OOP ?You know php.net ?You know arrays ?
3
What is SPL ?
4
Standard PHP Libraryinterfaces, classes and methods
solve common development problems
As of 5.3 SPL cannot be turned off from the source !
Why use SPL ?
5
SPL provides a huge toolkit that assists you to easily iterate over a diversity of data structures in a standardized way
What does it provide ?
6
• ArrayObject - approach arrays as objects
• Iterators - various iterators
• Interfaces - Countable Interface
• Exceptions - exceptions to streamline errorhandling
• SPL Functions - extra functions and autoloader func
• SplFileInfo - tools for filesystem access
• Datastructures - structuring data sequences
ArrayObject
• provides an interface
- treat arrays as objects
- elements are iteratable
7
ArrayObject methods• ArrayObject::append
• ArrayObject::__construct
• ArrayObject::count
• ArrayObject::getIterator
• ArrayObject::offsetExists
• ArrayObject::offsetGet
• ArrayObject::offsetSet
• ArrayObject::offsetUnset
8
ArrayObject w/o SPL<?php// file: nospl_arrayobject01.php
$myArray = array ( "monkey" => "bananas", "rabbit" => "carrots", "ogre" => "onions",);
echo "Ogres exists ? " . (key_exists('ogre', $myArray) ? "Yes" : "No") . "\n";
echo "Ogres equals " . $myArray['ogre'] . "\n";
9
ArrayObject Example<?php// file: spl_arrayobject01.php
$myArray = array ( "monkey" => "bananas", "rabbit" => "carrots", "ogre" => "onions",);
// create an object of the array$arrayObj = new ArrayObject($myArray);
echo "Ogres exists ? " . ($arrayObj->offsetExists("ogre") ? "Yes" : "No") . "\n";
echo "Ogres equals " . $arrayObj->offsetGet("ogre") . "\n";
10
ArrayObject Output$ /usr/bin/php ./nospl_arrayobject01.php Ogres exists ? YesOgres equals onionsExecution time: 0.00064299999999995 microseconds.
$ /usr/bin/php ./spl_arrayobject01.php Ogres exists ? YesOgres equals onionsExecution time: 0.00054399999999999 microseconds.
11
Iterator
• move back and forth in a stack
• distinct methods to access keys and values
12
Iterators• ArrayIterator
• CachingIterator
• RecursiveCachingIterator
• DirectoryIterator
• RecursiveDirectoryIterator
• FilterIterator
• LimitIterator
• ParentIterator
• RecursiveIteratorIterator
13
The ArrayIterator
iteration methods on array objects
14
ArrayIterator Example Case
• Array with 3 elements
- monkey => bananas,
- rabbit => carrots,
- ogre => onions
• display total elements
• display key/value pairs while looping
• display key/value pair for 2nd element
15
ArrayIterator w/o SPL<?php// file: nospl_iterator01.php$myArray = array ( "monkey" => "bananas", "rabbit" => "carrots", "ogre" => "onions",);echo "\$myArray has {sizeof($myArray)} elements\n";foreach ($myArray as $key => $value) { echo "{$key}: {$value}\n";}reset($myArray);next($myArray);echo "elem 2:" . key($myArray) . ": " . current($myArray) . "\n";
16
ArrayIterator w/ SPL<?php// file: spl_iterator01.php$myArray = array ( “monkey” => “bananas”, “rabbit” => “carrots”, “ogre” => “onions”,);$arrayObj = new ArrayObject($myArray);$iterator = $arrayObj->getIterator();echo "\$myArray has {$arrayObj->count()} elements\n";while ($iterator->valid()) { echo "{$iterator->key()}: {$iterator->current()}\n"; $iterator->next();}$iterator->seek(1);echo "elem 2:{$iterator->key()}: {$iterator->current()}\n";
17
ArrayIterator Output$ /usr/bin/php ./nospl_iterator01.php $myArray has 3 elementsmonkey: bananasrabbit: carrotsogre: onionselem 2:rabbit: carrotsExecution time: 0.0020509999999999 microseconds.
$ /usr/bin/php ./spl_iterator01.php $myArray has 3 elementsmonkey: bananasrabbit: carrotsogre: onionselem 2:rabbit: carrotsExecution time: 0.001346 microseconds.
18
Interfaces
• Countable
- provides an internal counter
• SeekableIterator
- provides an internal stack seeker
19
Countable Example<?php//file: spl_countable01.phpclass TequillaCounter implements Countable{ public function count() { static $count = 0; return ++$count; } public function order() { $order = $this->count(); echo ($order > 3 ? "Floor!" : "{$order} tequilla") . PHP_EOL; }}
20
Countable continued...$shots = new TequillaCounter();$shots->order();$shots->order();$shots->order();$shots->order();
Output:$ /usr/bin/php ./countable01.php1 tequilla2 tequilla3 tequillaFloor!
21
SPL Exceptions• SPL Exceptions
- templates
- throw exceptions
- common issues
• Types of exceptions
- LogicExceptions
- RuntimeExceptions
22
SPL LogicException Tree
23
SPL RuntimeException Tree
24
Exceptions Example<?php//file: spl_exception01.phpclass MyClass{ public function giveANumberFromOneToTen($number) { if($number < 1 || $number > 10) { throw new OutOfBoundsException('Number should be between 1 and 10'); } echo $number . PHP_EOL; }}
$my = new MyClass();try { $my->giveANumberFromOneToTen(5); $my->giveANumberFromOneToTen(20);} catch (OutOfBoundsException $e) { echo $e->getMessage() . PHP_EOL;}
Output:$ /usr/bin/php ./spl_exception01.php5Number should be between 1 and 10
25
SPL Functions• class_implements
Return the interfaces which are implemented by the given class
• class_parentsReturn the parent classes of the given class
• iterator_applyApply a user function to every element of an iterator
• iterator_countCount the elements in an iterator
• iterator_to_arrayCopy the iterator into an array
• spl_autoload_callTry all registered __autoload() function to load requested class
26
SPL Functions (2)• spl_autoload_functions
Return all registered __autoload() functions
• spl_autoload_registerRegister given function as __autoload() implementation
• spl_autoload_unregisterUnregister given function as __autoload() implementation
• spl_autoloadDefault implementation for __autoload()
• spl_classesReturn available SPL classes
• spl_object_hashReturn hash id for given object
27
SplFunctions Example<?php
interface foo {}interface bar {}
class baz implements foo, bar {}class example extends baz {}
var_dump(class_implements(new baz));
var_dump(class_implements(new example));
28
Output of SplFunctionsarray(2) { ["foo"]=> string(3) "foo" ["bar"]=> string(3) "bar"}array(2) { ["bar"]=> string(3) "bar" ["foo"]=> string(3) "foo"}
29
SplFileInfo• SplFileInfo::__construct
• SplFileInfo::getATime
• SplFileInfo::getBasename
• SplFileInfo::getCTime
• SplFileInfo::getFileInfo
• SplFileInfo::getFilename
• SplFileInfo::getGroup
• SplFileInfo::getInode
• SplFileInfo::getLinkTarget
• SplFileInfo::getMTime
• SplFileInfo::getOwner
• SplFileInfo::getPath
• SplFileInfo::getPathInfo
• SplFileInfo::getPathname
• SplFileInfo::getPerms
30
SplFileInfo (2)• SplFileInfo::getRealPath
• SplFileInfo::getSize
• SplFileInfo::getType
• SplFileInfo::isDir
• SplFileInfo::isExecutable
• SplFileInfo::isFile
• SplFileInfo::isLink
• SplFileInfo::isReadable
• SplFileInfo::isWritable
• SplFileInfo::openFile
• SplFileInfo::setFileClass
• SplFileInfo::setInfoClass
• SplFileInfo::__toString
31
SplFileInfo Example<?php
// use the current file to get information from$file = new SplFileInfo(dirname(__FILE__));
var_dump($file->isFile());var_dump($file->getMTime());var_dump($file->getSize());var_dump($file->getFileInfo());var_dump($file->getOwner());
//outputbool(false)int(1244760945)int(408)object(SplFileInfo)#2 (0) {}int(501)
32
Data Structures• Available in PHP 5.3.x
- SplDoublyLinkedList✓ SplStack✓ SplQueue✓ SplHeap✓ SplMaxHeap✓ SplMinHeap✓ SplPriorityQueue
33
Data Structures Example<?php// file: spl_stack01.php$stack = new SplStack();$stack->push('Message 1');$stack->push('Message 2');$stack->push('Message 3');
echo $stack->pop() . PHP_EOL;echo $stack->pop() . PHP_EOL;echo $stack->pop() . PHP_EOL;
Outputs:$ /usr/bin/php ./spl_stack01.php Message 3Message 2Message 1
34
Not a bridge too far...
35
Conclusion
SPL can help you solve common PHP issuesit’s built-in, so why not use it
it requires no “advanced skills” to use
36
Only one minor thing...
37
• php.net/spl needs more documentation !
• you can help on that part:
- see http://elizabethmariesmith.com/2009/02/setting-up-phd-on-windows
- you can set up phpdoc on each platform !
- Efnet: #php.doc channel
- http://doc.php.net - [email protected]
38
Documentation problem
39
• main SPL documentation:http://php.net/spl
• PHPro Tutorials on SPL:http://www.phpro.org/tutorials/Introduction-to-SPL.html
• Lorenzo Alberton’s blog:http://www.alberton.info/php_5.3_spl_data_structures.html
• http://www.colder.ch/news/01-08-2009/34/splobjectstorage-for-a-fa.html
More about SPL...
LicenseThis presentation is released under the Creative Commons Attribution-Share Alike 3.0 Unported LicenseYou are free:- to share : to copy, distribute and transmit the work
- to remix : to adapt the work
Under the following conditions:- attribution : You must attribute the work in the manner specified by the author or licensor
- share alike : If you alter, transform, or build upon this work, you may distribute the resulting work only under the same, similar or a compatible license
See: http://creativecommons.org/licenses/by-sa/3.0/
40
Credits
Golden Gate Bridge - Felix De Vliegherhttp://www.flickr.com/photos/felixdv/2883471022/
41
Find my slides on http://slideshare.net/DragonBe
Don’t forget to vote !http://joind.in/586
Thank you
42