SPL, not a bridge too far

Loading...

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

1 comments

Comments 1 - 1 of 1 previous next Post a comment

  • + guestc4db8b guestc4db8b 4 months ago
    Am I missing something, or have you completely missed the point with much of SPL?
    ArrayObject is pretty much what it says it is. It acts just like an array, but is an object.

    <?php

    $myArray = array(
    ’monkey’ => ’bananas’,
    ’rabbit’ => ’carrots’,
    ’ogre’ => ’onions’ );

    $arrayObj = new ArrayObject($myArray);
    echo count($arrayObj) . ’\n’; // 3 because it implements Countable
    echo ’Ogres exist ? ’ . (array_key_exists(’ogre’, $arrayObj) ? ’Yes’ : ’No’) . ’\n’;
    //or
    echo ’Ogres exist ? ’ . (isset($arrayObj[’ogre’]) ? ’Yes’ : ’No’) . ’\n’; echo ’Ogres eat ’ . $arrayObj[’ogre’] . ’\n’;

    $arrayObj->ksort();
    //getIterator() gets called implicitly
    foreach($arrayObj as $key => $value){
    echo $key . ’ eats ’ . $value . ’\n’;
    }
    ?>
    outputs:
    Ogres exist ? Yes
    Ogres exist ? Yes
    Ogres eat onions
    monkey eats bananas
    ogre eats onions
    rabbit eats carrots

    You’re right though in regards to documentation. It’s seriously lacking, and therefore most of the examples found online don’t show what SPL actually does.
Post a comment
Embed Video
Edit your comment Cancel

Notes on slide 1

Promotion of SPL




Definition of SPL

SPL functions
- base class functions
- autoloading functions





































3 Favorites

SPL, not a bridge too far - Presentation Transcript

  1. SPL, not a bridge too far Dutch PHP Conference 2009 - Amsterdam
  2. Who am I ? Michelangelo van Dam Independent Enterprise PHP consultant @dragonbe http://dragonbe.com 2
  3. Who are you ? You know OOP ? You know php.net ? You know arrays ? 3
  4. What is SPL ? Standard PHP Library interfaces, classes and methods solve common development problems As of 5.3 SPL cannot be turned off from the source ! 4
  5. Why use SPL ? SPL provides a huge toolkit that assists you to easily iterate over a diversity of data structures in a standardized way 5
  6. What does it provide ? • 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 6
  7. ArrayObject • provides an interface - treat arrays as objects - elements are iteratable 7
  8. ArrayObject methods • ArrayObject::append • ArrayObject::__construct • ArrayObject::count • ArrayObject::getIterator • ArrayObject::offsetExists • ArrayObject::offsetGet • ArrayObject::offsetSet • ArrayObject::offsetUnset 8
  9. <?php ArrayObject w/o SPL // 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
  10. <?php ArrayObject Example // 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
  11. ArrayObject Output $ /usr/bin/php ./nospl_arrayobject01.php Ogres exists ? Yes Ogres equals onions Execution time: 0.00064299999999995 microseconds. $ /usr/bin/php ./spl_arrayobject01.php Ogres exists ? Yes Ogres equals onions Execution time: 0.00054399999999999 microseconds. 11
  12. Iterator • move back and forth in a stack • distinct methods to access keys and values 12
  13. Iterators • ArrayIterator • CachingIterator • RecursiveCachingIterator • DirectoryIterator • RecursiveDirectoryIterator • FilterIterator • LimitIterator • ParentIterator • RecursiveIteratorIterator 13
  14. The ArrayIterator iteration methods on array objects 14
  15. 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
  16. <?php ArrayIterator w/o SPL // 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
  17. <?php ArrayIterator w/ SPL // 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
  18. ArrayIterator Output $ /usr/bin/php ./nospl_iterator01.php $myArray has 3 elements monkey: bananas rabbit: carrots ogre: onions elem 2:rabbit: carrots Execution time: 0.0020509999999999 microseconds. $ /usr/bin/php ./spl_iterator01.php $myArray has 3 elements monkey: bananas rabbit: carrots ogre: onions elem 2:rabbit: carrots Execution time: 0.001346 microseconds. 18
  19. Interfaces • Countable - provides an internal counter • SeekableIterator - provides an internal stack seeker 19
  20. <?php Countable Example //file: spl_countable01.php class 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
  21. Countable continued... $shots = new TequillaCounter(); $shots->order(); $shots->order(); $shots->order(); $shots->order(); Output: $ /usr/bin/php ./countable01.php 1 tequilla 2 tequilla 3 tequilla Floor! 21
  22. SPL Exceptions • SPL Exceptions - templates - throw exceptions - common issues • Types of exceptions - LogicExceptions - RuntimeExceptions 22
  23. SPL LogicException Tree 23
  24. SPL RuntimeException Tree 24
  25. <?php Exceptions Example //file: spl_exception01.php class 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.php 5 Number should be between 1 and 10 25
  26. SPL Functions • class_implements Return the interfaces which are implemented by the given class • class_parents Return the parent classes of the given class • iterator_apply Apply a user function to every element of an iterator • iterator_count Count the elements in an iterator • iterator_to_array Copy the iterator into an array • spl_autoload_call Try all registered __autoload() function to load requested class 26
  27. SPL Functions (2) • spl_autoload_functions Return all registered __autoload() functions • spl_autoload_register Register given function as __autoload() implementation • spl_autoload_unregister Unregister given function as __autoload() implementation • spl_autoload Default implementation for __autoload() • spl_classes Return available SPL classes • spl_object_hash Return hash id for given object 27
  28. <?php SplFunctions Example 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
  29. Output of SplFunctions array(2) { [\"foo\"]=> string(3) \"foo\" [\"bar\"]=> string(3) \"bar\" } array(2) { [\"bar\"]=> string(3) \"bar\" [\"foo\"]=> string(3) \"foo\" } 29
  30. SplFileInfo • SplFileInfo::__construct • SplFileInfo::getLinkTarget • SplFileInfo::getATime • SplFileInfo::getMTime • SplFileInfo::getBasename • SplFileInfo::getOwner • SplFileInfo::getCTime • SplFileInfo::getPath • SplFileInfo::getFileInfo • SplFileInfo::getPathInfo • SplFileInfo::getFilename • SplFileInfo::getPathname • SplFileInfo::getGroup • SplFileInfo::getPerms • SplFileInfo::getInode 30
  31. SplFileInfo (2) • SplFileInfo::getRealPath • SplFileInfo::isReadable • SplFileInfo::getSize • SplFileInfo::isWritable • SplFileInfo::getType • SplFileInfo::openFile • SplFileInfo::isDir • SplFileInfo::setFileClass • SplFileInfo::isExecutable • SplFileInfo::setInfoClass • SplFileInfo::isFile • SplFileInfo::__toString • SplFileInfo::isLink 31
  32. <?php SplFileInfo Example // 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()); //output bool(false) int(1244760945) int(408) object(SplFileInfo)#2 (0) { } int(501) 32
  33. Data Structures • Available in PHP 5.3.x - SplDoublyLinkedList ✓ SplStack ✓ SplQueue ✓ SplHeap ✓ SplMaxHeap ✓ SplMinHeap ✓ SplPriorityQueue 33
  34. 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 3 Message 2 Message 1 34
  35. Not a bridge too far... 35
  36. Conclusion SPL can help you solve common PHP issues it’s built-in, so why not use it it requires no “advanced skills” to use 36
  37. Only one minor thing... 37
  38. Documentation problem • 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 - phpdoc@php.net 38
  39. More about SPL... • 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 39
  40. License This presentation is released under the Creative Commons Attribution-Share Alike 3.0 Unported License You 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
  41. Credits Golden Gate Bridge - Felix De Vliegher http://www.flickr.com/photos/felixdv/2883471022/ 41
  42. Thank you Find my slides on http://slideshare.net/DragonBe Don’t forget to vote ! http://joind.in/586 42

+ Michelangelo van DamMichelangelo van Dam, 4 months ago

custom

1344 views, 3 favs, 0 embeds more stats

With this presentation I hope to show that using SP more

More info about this document

CC Attribution-ShareAlike LicenseCC Attribution-ShareAlike License

Go to text version

  • Total Views 1344
    • 1344 on SlideShare
    • 0 from embeds
  • Comments 1
  • Favorites 3
  • Downloads 64
Most viewed embeds

more

All embeds

less

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate. If needed, use the feedback form to let us know more details.

Cancel
File a copyright complaint
Having problems? Go to our helpdesk?

Categories