Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Spl to the Rescue - Zendcon 09

2,190 views

Published on

Given at Zendcon 2009 this is the improved version of the one hour SPL talk and you're missing the audience interaction fun.

Published in: Technology, Education
  • Be the first to comment

Spl to the Rescue - Zendcon 09

  1. 1. Standard Tools for Everyday Programming
  2. 2. Whoami http://elizabethmariesmith.com Work at http://omniti.com PHP-GTK PECL cairo WinGui Bad bad bad things to PHP (on windows) Twitter @auroraeosrose IRC auroraeosrose
  3. 3. Community Heckling On twitter #zendcon IRC is open, I can see backlog – constructive criticism is good Comment on http://joind.in/talk/view/934 No comments on hair, clothes, or my fat belly – constructive criticism is welcome ;)
  4. 4. Get the party started!
  5. 5. I have a ProblemRecursively iterate through directoriesFind all .jpg filesCheck last modified datesMove the ones older than two years to new location
  6. 6. How should I do this? Some nasty recursive use of scandir() to get my lists Or PHP’s dir() function and looping array_map() with a convoluted callback Glob + foreach madnessI think I’m going to need a lot of code….
  7. 7. SPL to the Rescue!  RecursiveDirectoryIterator  RecursiveIteratorIterator  FilterIterator  SplFileInfo What fun tools we have!
  8. 8. And not the kind you kick out of IRC
  9. 9. What is SPL? tandard HP ibrary A library of standard interfaces, classes, and functions designed to solve common programming problems and allow engine overloading.
  10. 10. Zod says – kneel before me!No… waitExplain in English Now! Because no one understood a word of that…
  11. 11. What is SPL?1. Engine overloading hooks via interfaces  Countable, SeekableIterator, RecursiveIterator2. Classes that utilize the interfaces  ArrayObject, MultipleIterator, DirectoryIterator3. Standard Class Implementations  Exceptions, SplStorage4. Functions to help with autoloading and objects  spl_autoload_register(), spl_classes(), iterator_apply()
  12. 12. But… it’s an extension right? SPL is an extension SPL is a core extension SPL cannot be built shared SPL should not be turned off SPL is present in PHP since 5.0 (almost 5 years ago) As of 5.3, SPL cannot be turned off without altering sourceIf you don’t have SPL, whoever built your PHP is an idiot(or an evil genius – it’s HARD).
  13. 13. Stuff that’s NOT in SPL Engine Defined interfaces you should know about!  ArrayAccess  Serializable  Iterator  IteratorAggregate  Traversable
  14. 14. Helper functions from SPL to you
  15. 15. Built in Autoloader spl_autoload() – default autoload implementation spl_autoload_extensions() – ext for spl_autoload()
  16. 16. Autoload Stack spl_autoload_register() – add an autoload to the stack spl_autoload_unregister() – remove an autoloader spl_autoload_functions() – what’s on the stack spl_autoload_call() – load something through the stack
  17. 17. Isn’t __autoload good enough? Combining different libraries with different naming conventions Dealing with different types of files (templates, classes) in different locations Changing autoload in use during runtime
  18. 18. Object Helper Functions class_implements() class_parents() spl_object_hash()Why are these not in core?Zod does not know… Zod demands you kneel!
  19. 19. Nothing but Templates
  20. 20. BadFunctionCallException BadMethodCall DomainExceptionLogicException InvalidArgumentException LengthExceptionExceptionClasses OutofRangeException
  21. 21. OutofBoundsException OverflowException RuntimeException RangeException UnderflowExceptionExceptionClasses UnexpectedValueException
  22. 22. So what does SPL offer? A standard set of Exceptions that all inherit from PHP’s Exception base class A standard way to set up exceptions by kind Do I recommend it? Depends on your application.
  23. 23. Foreach is your bestest friend! Foreach an object today!
  24. 24. What the heck is an iterator? A design pattern that is a generic solution to the problem of iterating over data in a consistent manner. Access the elements of an aggregate object sequentially without exposing its underlying representation.
  25. 25. Why do I care? Ever need to go over a list of items returned from a database? (well, duh) Or need to go over a list of items returned from a webservice? Ever used foreach? (or its slower, lesser cousin for?)
  26. 26. Foreach it baby! Foreach is your friend iterators give your code consistent usage and you can add more functionality
  27. 27. You can also… Extend Iterators to do what you need Chain Iterators: iteratoriteratoriteratoriterator
  28. 28. Meet the Iterator Interface
  29. 29. So how is it different?Array $ar= array(); Iterator $it = new Iterator; can be rewound  Might be rewindable  reset($ar)  $it->rewind() is valid unless the key is NULL  should know if there is a value  !is_null(key($ar))  $it->valid() Has a current value  Might have a current value or  current($ar) key Has keys  $it->key()  key($ar)  $it->current() can move forward  Can move forward  next($ar)  $it->next()
  30. 30. An Iterator for every occasion RecursiveIterator • CachingIterator RecursiveIteratorIterator • RecursiveCachingIterator OuterIterator • NoRewindIterator IteratorIterator • AppendIterator FilterIterator • RecursiveIteratorIterator RecursiveFilterIterator • InfiniteIterator ParentIterator • RegexIterator SeekableIterator • RecursiveRegexIterator LimitIterator • EmptyIterator GlobIterator • RecursiveTreeIterator • ArrayIterator
  31. 31. Why foreach is so dang useful ….
  32. 32. Innie or an Outie?  OuterIterator (interface)  Extends Iterator  Puts a wrapper around an iterator inside  Has one additional method – getInnerIterator() that should be implemented
  33. 33. Loopety Loop RecursiveIterator (interface)  Has two additional methods to implement  getChildren should return the sub-iterator for the current element – and it must return an object that implements recursiveIterator  hasChildren
  34. 34. Jumping ahead?  SeekableIterator (interface)  Additional method – seek(string $position)  Lets you jump to a specific spot to start iterating
  35. 35. Now on to classes Classes implement interfaces plus provide additional functionality Interfaces need you to fill in all the the required methods You can implement multiple interfaces You can’t extend multiple classesChoose Wisely
  36. 36. FilterIterator Abstract Class Has one method that must be implemented – accept – which should return true or false File filtering example at the beginning used this Highly useful for many types of iteration FilterIterator OuterIterator Iterator Traversable
  37. 37. IteratorIterator Regular Class Stick in something that implements traversable Voila – instant iterator IteratorIterator OuterIterator Iterator Traversable
  38. 38. ArrayIterator Regular Class Iterates an array – OR the public properties of an object! (neat trick – dirty trick) ArrayAccess and ArrayIterator SeekableIterator Iterator Traversable Countable too!
  39. 39. RecursiveIteratorIterator Regular Class Like IteratorIterator only recursive to boot RecursiveIteratorIterator OuterIterator Iterator Traversable
  40. 40. ParentIterator Regular Class Filter out stuff without children ParentIterator OuterIterator Iterator Traversable
  41. 41. LimitIterator Regular Class Like mysql’s limit – pick your range and offset and foreach away! LimitIterator OuterIterator Iterator Traversable
  42. 42. CachingIterator Regular Class Manages another iterator by checking whether it has more elements each time using a hasNext() method CachingIterator OuterIterator Iterator Traversable
  43. 43. RecursiveCachingIterator Regular Class Just like caching iterator only – believe it or not – recursive! RecursiveCachingIterator CachingIterator OuterIterator Iterator Traversable
  44. 44. DirectoryIterator Regular Class Makes going through directories a snap isDot, isFile – I love you SplFileInfo DirectoryIterator Iterator Traversable (extends)
  45. 45. RecursiveDirectoryIterator Regular Class Like, do it again… and again… and again… and… DirectoryIterator RecursiveIterator Iterator Traversable (extends)
  46. 46. RegexIterator Regular Class Filter an iterator by a regex Pick how you want it to match FilterIterator IteratorIterator Iterator Traversable (extends) (extends)
  47. 47. Iterator Helper Functions iterator_apply() – like array_walk iterator_count() – count the items iterator_to_array() – run the iterator, put results in array
  48. 48. Is it an array? An object? Why… it’s both!
  49. 49. ArrayAccess Interface
  50. 50. ArrayObject A class, NOT an interface It’s like arrayaccess on RedBull Highlights  exchangeArray  getArrayCopy (get your internally stored data)  Sorting methods  ksort et al
  51. 51. Countable Interface you can implement with any class (not iterator specific, but used a lot for it) Implement the count method and you can use the count() PHP function on any object
  52. 52. SplObjectStorage This does not do what you think it does Use objects as array keys, uniquely, with no collision issues (you might get them from spl_object_hash) Remember you need the object to get the data back out, unless you’re simply iterating over the contents Regular class, no need to extend and fill in methods http://www.colder.ch/news/01-08- 2009/34/splobjectstorage-for-a-fa.html
  53. 53. SplObserver and SplSubject Abstract classes for anything using an observer pattern http://www.a-scripts.com/object-oriented- php/2009/02/21/the-observer-pattern/ - great common sense tutorial If you do event/observers in your code, extending these two makes good sense
  54. 54. SplFileInfo fancy class for a file all the file system functions in compact object form  getMTime == filemtime  openFile == fopen
  55. 55. Beyond arrays to the wild wild west of 5.3
  56. 56. Hmmm….I think we need a bettercontainer for all this stuff…
  57. 57. Arrays and Objects General purpose containers Have same C structure (HashTable) holding the data underneath C has other ways of holding data that can be faster when scaled
  58. 58. Lies, damn Lies, and statistics Great set of benchmarks by Matthew Turland http://www.slideshare.net/tobias382/new-spl- features-in-php-53 Generally, not useful for small amounts of data, highly useful for large (think thousands) of pieces of data
  59. 59. SPLFixedArray A fixed length, int key only array Why? It’s faster because it stores data differently “under the hood” in C Regular class, don’t need to extend and fill in any methods
  60. 60. Stacks and Linked Lists
  61. 61. New and Shiny SplDoublyLinkedList SplStack SplQueue
  62. 62. Implementations Stack does LIFO Queue does FIFO See improvements when constantly updating the stack Less improvement seen with a straight stick everything in and remove everything at once
  63. 63. Heap 17 16 15 14 13 12 11 10 9 8 7 6 5 4 32 1
  64. 64. More Data Structures SplHeap SplPriorityQueue SplMaxHeap SplMinHeap
  65. 65. Implementations MinHeap - key 1 < or = key 2 MaxHeap – key 1 > or = key 2 PriorityQueue – constantly sorting by priority as new things are put in
  66. 66. The Documentation Problem http://elizabethmariesmith.com/2009/02/setting-up- phd-on-windows/ - you can write docbook on any platform! Efnet - #php.doc channel http://doc.php.net phpdoc@lists.php.net – mailing list See me and start helping today!
  67. 67. Resources http://php.net/spl - spl docs http://php.net/~helly/php/ext/spl - Doxygen docs http://www.alberton.info/articles/filter/tag/SPL - some great datastorage related tutorials http://www.phpro.org/tutorials/Introduction-to- SPL.html - more great SPL tutorials auroraeosrose@php.net

×