42
SPL, not a bridge too far Dutch PHP Conference 2009 - Amsterdam

SPL, not a bridge too far

Embed Size (px)

Citation preview

Page 1: SPL, not a bridge too far

SPL, not a bridge too farDutch PHP Conference 2009 - Amsterdam

Page 2: SPL, not a bridge too far

Who am I ?

2

Michelangelo van DamIndependent Enterprise PHP consultant

@dragonbe

http://dragonbe.com

Page 3: SPL, not a bridge too far

Who are you ?

You know OOP ?You know php.net ?You know arrays ?

3

Page 4: SPL, not a bridge too far

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 !

Page 5: SPL, not a bridge too far

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

Page 6: SPL, not a bridge too far

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

Page 7: SPL, not a bridge too far

ArrayObject

• provides an interface

- treat arrays as objects

- elements are iteratable

7

Page 8: SPL, not a bridge too far

ArrayObject methods• ArrayObject::append

• ArrayObject::__construct

• ArrayObject::count

• ArrayObject::getIterator

• ArrayObject::offsetExists

• ArrayObject::offsetGet

• ArrayObject::offsetSet

• ArrayObject::offsetUnset

8

Page 9: SPL, not a bridge too far

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

Page 10: SPL, not a bridge too far

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

Page 11: SPL, not a bridge too far

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

Page 12: SPL, not a bridge too far

Iterator

• move back and forth in a stack

• distinct methods to access keys and values

12

Page 13: SPL, not a bridge too far

Iterators• ArrayIterator

• CachingIterator

• RecursiveCachingIterator

• DirectoryIterator

• RecursiveDirectoryIterator

• FilterIterator

• LimitIterator

• ParentIterator

• RecursiveIteratorIterator

13

Page 14: SPL, not a bridge too far

The ArrayIterator

iteration methods on array objects

14

Page 15: SPL, not a bridge too far

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

Page 16: SPL, not a bridge too far

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

Page 17: SPL, not a bridge too far

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

Page 18: SPL, not a bridge too far

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

Page 19: SPL, not a bridge too far

Interfaces

• Countable

- provides an internal counter

• SeekableIterator

- provides an internal stack seeker

19

Page 20: SPL, not a bridge too far

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

Page 21: SPL, not a bridge too far

Countable continued...$shots = new TequillaCounter();$shots->order();$shots->order();$shots->order();$shots->order();

Output:$ /usr/bin/php ./countable01.php1 tequilla2 tequilla3 tequillaFloor!

21

Page 22: SPL, not a bridge too far

SPL Exceptions• SPL Exceptions

- templates

- throw exceptions

- common issues

• Types of exceptions

- LogicExceptions

- RuntimeExceptions

22

Page 23: SPL, not a bridge too far

SPL LogicException Tree

23

Page 24: SPL, not a bridge too far

SPL RuntimeException Tree

24

Page 25: SPL, not a bridge too far

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

Page 26: SPL, not a bridge too far

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

Page 27: SPL, not a bridge too far

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

Page 28: SPL, not a bridge too far

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

Page 29: SPL, not a bridge too far

Output of SplFunctionsarray(2) { ["foo"]=> string(3) "foo" ["bar"]=> string(3) "bar"}array(2) { ["bar"]=> string(3) "bar" ["foo"]=> string(3) "foo"}

29

Page 30: SPL, not a bridge too far

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

Page 31: SPL, not a bridge too far

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

Page 32: SPL, not a bridge too far

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

Page 33: SPL, not a bridge too far

Data Structures• Available in PHP 5.3.x

- SplDoublyLinkedList✓ SplStack✓ SplQueue✓ SplHeap✓ SplMaxHeap✓ SplMinHeap✓ SplPriorityQueue

33

Page 34: SPL, not a bridge too far

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

Page 35: SPL, not a bridge too far

Not a bridge too far...

35

Page 36: SPL, not a bridge too far

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

Page 37: SPL, not a bridge too far

Only one minor thing...

37

Page 38: SPL, not a bridge too far

• 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

Page 39: SPL, not a bridge too far

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...

Page 40: SPL, not a bridge too far

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

Page 41: SPL, not a bridge too far

Credits

Golden Gate Bridge - Felix De Vliegherhttp://www.flickr.com/photos/felixdv/2883471022/

41

Page 42: SPL, not a bridge too far

Find my slides on http://slideshare.net/DragonBe

Don’t forget to vote !http://joind.in/586

Thank you

42