spl to the rescue - zendcon 09

69
SPL to the Rescue Standard Tools for Everyday Programming

Upload: elizabeth-smith

Post on 08-May-2015

1.671 views

Category:

Technology


1 download

DESCRIPTION

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

TRANSCRIPT

  • 1.Standard Tools for Everyday Programming

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. 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. Get the partystarted! 5. I have a ProblemRecursively iterate through directoriesFind all .jpg filesCheck last modified datesMove the ones older than two years to new location 6. How should I do this? Some nasty recursive use of scandir() to get my lists Or PHPs dir() function and looping array_map() with a convoluted callback Glob + foreach madnessI think Im going to need a lot of code. 7. SPL to the Rescue! RecursiveDirectoryIterator RecursiveIteratorIterator FilterIterator SplFileInfoWhat fun tools we have! 8. And not the kind you kick out of IRC 9. What is SPL? tandard HP ibraryA library of standard interfaces, classes, and functions designed tosolve common programming problems and allow engineoverloading. 10. Zod says kneel before me!No waitExplain in English Now!Because no one understood aword of that 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 objectsspl_autoload_register(), spl_classes(), iterator_apply() 12. But its 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 alteringsourceIf you dont have SPL, whoever built your PHP is an idiot(or an evil genius its HARD). 13. Stuff thats NOT in SPL Engine Defined interfaces you should know about! ArrayAccess Serializable Iterator IteratorAggregate Traversable 14. Helper functions from SPL to you 15. Built in Autoloader spl_autoload() default autoload implementation spl_autoload_extensions() ext for spl_autoload() 16. Autoload Stack spl_autoload_register() add an autoload to the stack spl_autoload_unregister() remove an autoloader spl_autoload_functions() whats on the stack spl_autoload_call() load something through the stack 17. Isnt __autoload good enough? Combining different libraries with different namingconventions Dealing with different types of files (templates,classes) in different locations Changing autoload in use during runtime 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. Nothing but Templates 20. BadFunctionCallException BadMethodCallDomainExceptionLogicException InvalidArgumentException LengthExceptionExceptionClassesOutofRangeException 21. OutofBoundsException OverflowException RuntimeException RangeException UnderflowExceptionExceptionClasses UnexpectedValueException 22. So what does SPL offer? A standard set of Exceptions that all inherit fromPHPs Exception base class A standard way to set up exceptions by kind Do I recommend it? Depends on your application. 23. Foreach is your bestest friend! Foreach an object today! 24. What the heck is an iterator? A design pattern that is a generic solution to theproblem of iterating over data in a consistent manner. Access the elements of an aggregate objectsequentially without exposing its underlyingrepresentation. 25. Why do I care? Ever need to go over a list of items returned from adatabase? (well, duh) Or need to go over a list of items returned from awebservice? Ever used foreach? (or its slower, lesser cousin for?) 26. Foreach it baby! Foreach is your friend iterators give your code consistent usage and you can add more functionality 27. You can also Extend Iterators to do what you need Chain Iterators: iteratoriteratoriteratoriterator 28. Meet the Iterator Interface 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. 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. Why foreach is so dang useful . 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. Loopety Loop RecursiveIterator (interface) Has two additionalmethods to implement getChildren shouldreturn the sub-iteratorfor the current element and it must return anobject that implementsrecursiveIterator hasChildren 34. Jumping ahead? SeekableIterator(interface) Additional method seek(string $position) Lets you jump to a specific spot to start iterating 35. Now on to classes Classes implement interfaces plus provide additionalfunctionality Interfaces need you to fill in all the the requiredmethods You can implement multiple interfaces You cant extend multiple classesChoose Wisely 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. IteratorIterator Regular Class Stick in something that implements traversable Voila instant iterator IteratorIterator OuterIterator Iterator Traversable 38. ArrayIterator Regular Class Iterates an array OR the public properties of an object! (neat trick dirty trick) ArrayAccess and ArrayIterator SeekableIterator Iterator TraversableCountable too! 39. RecursiveIteratorIterator Regular Class Like IteratorIterator only recursive to boot RecursiveIteratorIterator OuterIterator Iterator Traversable 40. ParentIterator Regular Class Filter out stuff without children ParentIterator OuterIterator Iterator Traversable 41. LimitIterator Regular Class Like mysqls limit pick your range and offset and foreach away! LimitIterator OuterIterator IteratorTraversable 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. RecursiveCachingIterator Regular Class Just like caching iterator only believe it or not recursive! RecursiveCachingIterator CachingIterator OuterIterator Iterator Traversable 44. DirectoryIterator Regular Class Makes going through directories a snap isDot, isFile I love you SplFileInfo DirectoryIterator Iterator Traversable(extends) 45. RecursiveDirectoryIterator Regular Class Like, do it again and again and again and DirectoryIterator RecursiveIterator Iterator Traversable(extends) 46. RegexIterator Regular Class Filter an iterator by a regex Pick how you want it to matchFilterIterator IteratorIteratorIterator Traversable(extends)(extends) 47. Iterator Helper Functions iterator_apply() like array_walk iterator_count() count the items iterator_to_array() run the iterator, put results inarray 48. Is it an array? An object? Why its both! 49. ArrayAccess Interface 50. ArrayObject A class, NOT an interface Its like arrayaccess on RedBull Highlights exchangeArray getArrayCopy (get your internally stored data) Sorting methods ksort et al 51. Countable Interface you canimplement with anyclass (not iteratorspecific, but used a lotfor it) Implement the countmethod and you can usethe count() PHPfunction on any object 52. SplObjectStorage This does not do what you think it does Use objects as array keys, uniquely, with no collisionissues (you might get them from spl_object_hash) Remember you need the object to get the data backout, unless youre 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. 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. SplFileInfo fancy class for a file all the file system functions in compact object form getMTime == filemtime openFile == fopen 55. Beyond arrays to the wild wild west of 5.3 56. Hmmm.I think we need a bettercontainer for all this stuff 57. Arrays and Objects General purpose containers Have same C structure (HashTable)holding the data underneath C has other ways of holding data that canbe faster when scaled 58. Lies, damn Lies, and statistics Great set of benchmarks by Matthew Turlandhttp://www.slideshare.net/tobias382/new-spl-features-in-php-53 Generally, not useful for small amounts of data, highlyuseful for large (think thousands) of pieces of data 59. SPLFixedArray A fixed length, int key only array Why? Its faster because it stores data differentlyunder the hood in C Regular class, dont need to extend and fill in anymethods 60. Stacks and Linked Lists 61. New and Shiny SplDoublyLinkedList SplStackSplQueue 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. Heap171615 1413121110987654321 64. More Data StructuresSplHeap SplPriorityQueue SplMaxHeap SplMinHeap 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. 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 [email protected] mailing list See me and start helping today! 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 [email protected]