$30 off During Our Annual Pro Sale. View Details »

(Re)discovering the SPL - Sweetlake 14

Joshua Thijssen
September 05, 2014
42

(Re)discovering the SPL - Sweetlake 14

Joshua Thijssen

September 05, 2014
Tweet

Transcript

  1. 1
    Joshua Thijssen
    jaytaph
    (Re)discovering the SPL

    View Slide

  2. 2
    Joshua Thijssen
    Freelance consultant and trainer @ TechAdemy
    Founder of TechAnalyze.io
    Founder of the Dutch Web Alliance
    Blog: http://adayinthelifeof.nl
    Email: [email protected]
    Twitter: @jaytaph

    View Slide

  3. 3
    Q: Have you ever used the SPL?

    View Slide

  4. 4
    Q: Have you ever used the SPL
    without going nuts?

    View Slide

  5. 5
    SPL Documentation

    View Slide

  6. 5
    SPL Documentation
    http://www.php.net/spl

    View Slide

  7. 6

    View Slide

  8. 6

    View Slide

  9. 7

    View Slide

  10. 8

    View Slide

  11. ➡ Not enough documentation.
    8

    View Slide

  12. ➡ Not enough documentation.
    ➡ Very few examples.
    8

    View Slide

  13. ➡ Not enough documentation.
    ➡ Very few examples.
    ➡ Wrong / missing in some cases.
    8

    View Slide

  14. ➡ Interfaces
    ➡ Iterators
    ➡ Data structures
    ➡ Exceptions
    ➡ Miscellaneous functionality
    9
    Every SPL talk available:

    View Slide

  15. 10
    Don’t get scared!
    The SPL is awesomesauce!

    View Slide

  16. 11
    INTERFACES

    View Slide

  17. 12
    Traversable
    (not an “spl interface”)

    View Slide

  18. 13

    View Slide

  19. ➡ Traversable cannot be implemented.
    13

    View Slide

  20. ➡ Traversable cannot be implemented.
    ➡ Traversable can be detected (instanceof).
    13

    View Slide

  21. ➡ Traversable cannot be implemented.
    ➡ Traversable can be detected (instanceof).
    ➡ foreach() detects traversable interfaces and
    does magic things.
    13

    View Slide

  22. 14
    Iterator
    (still not an “spl interface”)

    View Slide

  23. Userland interface to make
    an object traversable
    15

    View Slide

  24. Iterator extends Traversable {
    /* Methods */
    abstract public mixed current ( void )
    abstract public scalar key ( void )
    abstract public void next ( void )
    abstract public void rewind ( void )
    abstract public boolean valid ( void )
    }
    16
    Iterator interface:

    View Slide

  25. 17

    View Slide

  26. ➡ Iterator
    17

    View Slide

  27. ➡ Iterator
    ➡ FilterIterators
    17

    View Slide

  28. ➡ Iterator
    ➡ FilterIterators
    ➡ “Chains” iterators together
    17

    View Slide

  29. ➡ Iterator
    ➡ FilterIterators
    ➡ “Chains” iterators together
    ➡ IteratorAggregate
    17

    View Slide

  30. ➡ Iterator
    ➡ FilterIterators
    ➡ “Chains” iterators together
    ➡ IteratorAggregate
    ➡ Is not an iterator, but HAS an iterator
    17

    View Slide

  31. 18
    1 2
    3 $bookCollection = array(
    4 new Book("50 shades of gray"),
    5 new Book("The Hobbit"),
    6 new Book("It"),
    7 array(
    8 new Book("Discworld: The colour of magic"),
    9 new Book("Discworld: A light fantastic"),
    10 ),
    11 array(
    12 new Book("Harry Potter and the deadly hallows"),
    13 /* ... */
    14 ),
    15 /* ... */
    16 );
    17
    18 foreach ($bookCollection as $book) {
    19 // Do something with a book, but how about book-series?
    20 }

    View Slide

  32. 19
    1 2
    3 $bookCollection = new BookCollection(
    4 array(
    5 new Book("50 shades of gray"),
    6 new Book("The Hobbit"),
    7 new Book("It"),
    8 array('Discworld' =>
    9 new Book("The colour of magic"),
    10 new Book("A light fantastic"),
    11 ),
    12 array('Harry Potter' =>
    13 new Book("Harry Potter and the deadly hallows"),
    14 /* ... */
    15 ),
    16 /* ... */
    17 ));
    18
    19 foreach ($bookCollection as $book) {
    20 // Do something with all single books
    21 }
    22
    23 foreach ($bookCollection->getSeries('Harry Potter')) {
    24 // Do something with just one serie
    25 }
    26
    27 $it = $bookCollection->getTopRatedBooks();
    28 $it2 = new LimitIterator($it, 0, 5);
    29 foreach ($it2 as $book) {
    30 // Do something with the top 5
    31 }
    32
    33 $it = $bookCollection->getTopRatedBooks();
    34 $it2 = new RegexIterator($it, '/(gray|colour)/');
    35 foreach ($it2 as $book) {
    36 // Do something with all books that have 'gray' or 'colour' in the title
    37 }

    View Slide

  33. 1 $dir = opendir(".");
    2 while (($file = readdir($dir)) !== false) {
    3
    4 # Business logic happens here
    5 print "file: $file\n";
    6
    7 }
    20

    View Slide

  34. 1 $dir = opendir(".");
    2 while (($file = readdir($dir)) !== false) {
    3
    4 # hack: filter only mp3 files
    5 if (! preg_match('|\.mp3$|i', $file)) {
    6 continue;
    7 }
    8
    9 # Business logic happens here
    10 print "file: $file\n";
    11 }
    21

    View Slide

  35. ➡ Filter all MP3 and all JPG files.
    22

    View Slide

  36. ➡ Filter all MP3 and all JPG files.
    ➡ Filter all MP3 files that are larger than
    6MB.
    22

    View Slide

  37. ➡ Filter all MP3 and all JPG files.
    ➡ Filter all MP3 files that are larger than
    6MB.
    ➡ Do not filter at all.
    22

    View Slide

  38. ➡ Filter all MP3 and all JPG files.
    ➡ Filter all MP3 files that are larger than
    6MB.
    ➡ Do not filter at all.
    ➡ Search sub-directories as well.
    22

    View Slide

  39. ➡ Filter all MP3 and all JPG files.
    ➡ Filter all MP3 files that are larger than
    6MB.
    ➡ Do not filter at all.
    ➡ Search sub-directories as well.
    ➡ Search multiple directories.
    22

    View Slide

  40. 23

    View Slide

  41. ➡ How to test? (we can’t)
    23

    View Slide

  42. ➡ How to test? (we can’t)
    ➡ How to maintain? (we can’t)
    23

    View Slide

  43. ➡ How to test? (we can’t)
    ➡ How to maintain? (we can’t)
    ➡ How to reuse? (we can’t)
    23

    View Slide

  44. 1 $it = new DirectoryIterator(".");
    2 foreach ($it as $fi) {
    3 print "File: ".$fi->getPathname()."\n";
    4 }
    24

    View Slide

  45. 1 $it = new DirectoryIterator(".");
    2 $it2 = new RegexIterator($it, "/\.mp3$/i");
    3 foreach ($it2 as $fi) {
    4 print "File: ".$fi->getPathname()."\n";
    5 }
    25

    View Slide

  46. 1 $it = new DirectoryIterator(".");
    2 $it2 = new RegexIterator($it, "/\.mp3$/i");
    3 $it3 = new FilesizeIterator($it2, 0, 6 * 1024 * 1024);
    4 $it4 = new LimitIterator($it3, 10, 5);
    5
    6 foreach ($it4 as $fi) {
    7 print "File: ".$fi->getPathname()."\n";
    8 }
    26

    View Slide

  47. 1 $it = new DirectoryIterator(".");
    2 $it2 = new RegexIterator($it, "/\.mp3$/i");
    3 $it3 = new FilesizeIterator($it2, 0, 6 * 1024 * 1024);
    4 $it4 = new LimitIterator($it3, 10, 5);
    5
    6 foreach ($it4 as $fi) {
    7 print "File: ".$fi->getPathname()."\n";
    8 }
    26

    View Slide

  48. 27

    View Slide

  49. ✓ Reusable
    We can use iterators where ever we want.
    27

    View Slide

  50. ✓ Reusable
    We can use iterators where ever we want.
    ✓ Testable
    Iterators can be tested separately.
    27

    View Slide

  51. ✓ Reusable
    We can use iterators where ever we want.
    ✓ Testable
    Iterators can be tested separately.
    ✓ Maintainable
    No need to adapt our business logic.
    27

    View Slide

  52. 28
    Countable
    (hurrah! An “spl interface”!)

    View Slide

  53. 1 class myIterator implements \Iterator {
    2 /* ... */
    3 }
    4
    5 $a = array(1, 2, 3);
    6 $it = new myIterator($a);
    7
    8 print count($it);
    29

    View Slide

  54. 1 class myIterator implements \Iterator {
    2 /* ... */
    3 }
    4
    5 $a = array(1, 2, 3);
    6 $it = new myIterator($a);
    7
    8 print count($it);
    1
    29

    View Slide

  55. 1 class myCountableIterator extends myIterator implements Countable {
    2 function count() {
    3 return count($this->_elements);
    4 }
    5 }
    6
    7 $a = array(1, 2, 3, 4, 5);
    8 $it = new myCountableIterator($a);
    9
    10 print count($it);
    30

    View Slide

  56. 1 class myCountableIterator extends myIterator implements Countable {
    2 function count() {
    3 return count($this->_elements);
    4 }
    5 }
    6
    7 $a = array(1, 2, 3, 4, 5);
    8 $it = new myCountableIterator($a);
    9
    10 print count($it);
    5
    30

    View Slide

  57. 1 class myCountableIterator extends myIterator implements Countable {
    2 function count() {
    3 return count($this->_arr);
    4 }
    5 }
    6
    7 $a = array(1, 2, 3, 4, 5);
    8 $it = new myCountableIterator($a);
    9 $it2 = new limitIterator($it, 0, 3);
    10
    11 print count($it2);
    31

    View Slide

  58. 1 class myCountableIterator extends myIterator implements Countable {
    2 function count() {
    3 return count($this->_arr);
    4 }
    5 }
    6
    7 $a = array(1, 2, 3, 4, 5);
    8 $it = new myCountableIterator($a);
    9 $it2 = new limitIterator($it, 0, 3);
    10
    11 print count($it2);
    1
    31

    View Slide

  59. 32
    ITERATORS

    View Slide

  60. SPL Iterators
    ➡ AppendIterator
    ➡ ArrayIterator
    ➡ CachingIterator
    ➡ CallbackFilterIterator
    ➡ DirectoryIterator
    ➡ EmptyIterator
    ➡ FilesystemIterator
    ➡ FilterIterator
    ➡ GlobIterator
    ➡ InfiniteIterator
    ➡ IteratorIterator
    ➡ LimitIterator
    ➡ MultipleIterator
    ➡ NoRewindIterator
    ➡ ParentIterator
    ➡ RecursiveArrayIterator
    ➡ RecursiveCachingIterator
    ➡ RecursiveCallbackFilterIterator
    ➡ RecursiveDirectoryIterator
    ➡ RecursiveFilterIterator
    ➡ RecursiveIteratorIterator
    ➡ RecursiveRegexIterator
    ➡ RecursiveTreeIterator
    ➡ RegexIterator
    ➡ SimpleXMLIterator
    33

    View Slide

  61. SPL Iterators
    34
    http://lxr.php.net/xref/PHP_5_5/ext/spl/internal/

    View Slide

  62. 35

    View Slide

  63. 36

    View Slide

  64. ➡ IteratorIterator?
    36

    View Slide

  65. ➡ IteratorIterator?
    ➡ RecursiveIterator?
    36

    View Slide

  66. ➡ IteratorIterator?
    ➡ RecursiveIterator?
    ➡ RecursiveIteratorIterator?
    36

    View Slide

  67. ➡ IteratorIterator?
    ➡ RecursiveIterator?
    ➡ RecursiveIteratorIterator?
    ➡ RecursiveCallbackFilterIterator?
    36

    View Slide

  68. ➡ IteratorIterator?
    ➡ RecursiveIterator?
    ➡ RecursiveIteratorIterator?
    ➡ RecursiveCallbackFilterIterator?
    36

    View Slide

  69. 37
    IteratorIterator

    View Slide

  70. 38
    Turns traversable “things” into an iterator

    View Slide

  71. 39
    1 $it = new myIterator();
    2 if ($it instanceof \IteratorAggregate) {
    3 $it = $it->getIterator();
    4 }
    5 $it2 = new \LimitIterator($it, 5, 10);

    View Slide

  72. 40
    1 $it = new myIterator();
    2 $it2 = new \IteratorIterator($it);
    3 $it3 = new \LimitIterator($it2, 5, 10);

    View Slide

  73. 41
    Recursive*Iterator

    View Slide

  74. 42
    1 $it = new ArrayIterator(
    2 array("foo", "bar", array("qux", "wox"), "baz"));
    3
    4 foreach ($it as $v) {
    5 print $v . "\n";
    6 }

    View Slide

  75. 42
    1 $it = new ArrayIterator(
    2 array("foo", "bar", array("qux", "wox"), "baz"));
    3
    4 foreach ($it as $v) {
    5 print $v . "\n";
    6 }
    foo
    bar
    Array
    baz

    View Slide

  76. 43
    1 $it = new RecursiveArrayIterator(
    2 array("foo", "bar", array("qux", "wox"), "baz"));
    3
    4 foreach ($it as $v) {
    5 print $v . "\n";
    6 }

    View Slide

  77. 43
    1 $it = new RecursiveArrayIterator(
    2 array("foo", "bar", array("qux", "wox"), "baz"));
    3
    4 foreach ($it as $v) {
    5 print $v . "\n";
    6 }
    foo
    bar
    Array
    baz

    View Slide

  78. 44
    1 $it = new RecursiveArrayIterator(
    2 array("foo", "bar", array("qux", "wox"), "baz"));
    3 $it2 = new RecursiveIteratorIterator($it);
    4
    5 foreach ($it2 as $v) {
    6 print $v . "\n";
    7 }

    View Slide

  79. 44
    1 $it = new RecursiveArrayIterator(
    2 array("foo", "bar", array("qux", "wox"), "baz"));
    3 $it2 = new RecursiveIteratorIterator($it);
    4
    5 foreach ($it2 as $v) {
    6 print $v . "\n";
    7 }
    foo
    bar
    qux
    wox
    baz

    View Slide

  80. 45
    “Recursive” iterators add the POSSIBILITY
    to recursively iterate over data.
    You still need to implement it!

    View Slide

  81. 46
    RecursiveCallbackFilterIterator

    View Slide

  82. ➡ Enables recursivity
    ➡ Is a filter iterator (does not necessarily
    return all the elements)
    ➡ Filters through a callback function.
    47

    View Slide

  83. 48
    SPL Iterators,..

    View Slide

  84. ➡ It has “quirks” that are easily solvable (but
    breaks BC)
    ➡ Documentation is not always up to date.
    ➡ Naming is VERY confusing (caching
    iterator, recursiveIterator, seekableIterator)
    ➡ But the iterators are worth it!
    49

    View Slide

  85. 50
    DATA STRUCTURES

    View Slide

  86. 51
    ➡ SplDoublyLinkedList
    ➡ SplStack
    ➡ SplQueue
    ➡ SplHeap
    ➡ SplMinHeap
    ➡ SplMaxHeap
    ➡ SplPriorityQueue
    ➡ SplFixedArray
    ➡ SplObjectStorage

    View Slide

  87. 52
    ➡ Every data structure has its strength and
    weaknesses.
    ➡ Big-Oh O(1), O(n), O(log n) etc...
    ➡ Balance between time (CPU) and space
    (memory)
    ➡ PHP arrays are quite good!
    ➡ But sometimes other data structures are
    better.

    View Slide

  88. 53
    PubQuiz

    View Slide

  89. 54
    http://www.flickr.com/photos/sostark/26697448/

    View Slide

  90. 54
    http://www.flickr.com/photos/sostark/26697448/
    SplStack

    View Slide

  91. 55

    View Slide

  92. 55
    SplQueue

    View Slide

  93. 56
    http://www.flickr.com/photos/blogchef/4764248456/sizes/z/in/photostream/

    View Slide

  94. 56
    http://www.flickr.com/photos/blogchef/4764248456/sizes/z/in/photostream/
    Spl(Doubly)LinkedList

    View Slide

  95. 57
    http://www.flickr.com/photos/pediddle/54326823/

    View Slide

  96. 57
    http://www.flickr.com/photos/pediddle/54326823/
    SplObjectStorage

    View Slide

  97. 58

    View Slide

  98. 58
    SplPriorityQueue

    View Slide

  99. 59
    http://farm4.static.flickr.com/3224/3072017987_ee454536da.jpg

    View Slide

  100. 59
    http://farm4.static.flickr.com/3224/3072017987_ee454536da.jpg
    SplHeap

    View Slide

  101. 60
    http://en.wikipedia.org/wiki/File:USA.NM.VeryLargeArray.02.jpg

    View Slide

  102. 60
    http://en.wikipedia.org/wiki/File:USA.NM.VeryLargeArray.02.jpg
    SplFixedArray

    View Slide

  103. 61
    ➡ Use wisely:
    ➡ Don’t use SplStack / SplQueue for
    random reads.
    ➡ Don’t use FixedArrays when you need
    speed boosts.

    View Slide

  104. 62
    EXCEPTIONS

    View Slide

  105. ➡ BadFunctionCallException
    ➡ BadMethodCallException
    ➡ DomainException
    ➡ InvalidArgumentException
    ➡ LengthException
    ➡ LogicException
    ➡ OutOfBoundsException
    ➡ OutOfRangeException
    ➡ OverflowException
    ➡ RangeException
    ➡ RuntimeException
    ➡ UnderflowException
    ➡ UnexpectedValueException
    63

    View Slide

  106. ➡ BadFunctionCallException
    ➡ BadMethodCallException
    ➡ DomainException
    ➡ InvalidArgumentException
    ➡ LengthException
    ➡ OutOfRangeException
    64
    Logic Exceptions Runtime Exceptions
    ➡ OutOfBoundsException
    ➡ OverflowException
    ➡ RangeException
    ➡ UnderflowException
    ➡ UnexpectedValueException

    View Slide

  107. 65
    1 function foo($str) {
    2 if ($str == "The Spanish Inquisition") {
    3 throw new \UnexpectedValueException("Nobody expects ".$str);
    4 }
    5 /* ... */
    6 }

    View Slide

  108. 66
    1 function foo($str) {
    2 if ($str == "The Spanish Inquisition") {
    3 throw new \InvalidArgumentException("Nobody expects ".$str);
    4 }
    5 /* ... */
    6 }
    Logic, not runtime

    View Slide

  109. 67
    1 function foo($str) {
    2 if ($str == "The Spanish Inquisition") {
    3 /* logic */
    4 throw new \InvalidArgumentException("Nobody expects ".$str);
    5 }
    6
    7 try {
    8 $this->getDatabase()->saveRecord($str);
    9 } catch (\RuntimeException $e) {
    10 /* We could try again here */
    11 } catch (\Exception $e) {
    12 /* Sorry, something else occurred. */
    13 }
    14 }

    View Slide

  110. 68
    Never throw “\Exception”
    Always catch “\Exception”

    View Slide

  111. 69
    MISC

    View Slide

  112. ➡ SPL Autoloading
    ➡ SplFileInfo class
    ➡ Spl(Temp)FileObject
    ➡ ArrayObject
    ➡ SplObserver / SplSubject
    70

    View Slide

  113. 71
    Autoloader

    View Slide

  114. 72
    spl_autoload_register("spl_autoload_call");

    View Slide

  115. 72
    spl_autoload_register("spl_autoload_call");
    Throws logicException

    View Slide

  116. 73
    spl_autoload_unregister("spl_autoload_call");

    View Slide

  117. 73
    spl_autoload_unregister("spl_autoload_call");
    - Removes ALL the autoloaders!
    - Destroys the autoload stack.
    - Set your house on fire.

    View Slide

  118. 74
    ArrayObject

    View Slide

  119. 75
    ArrayObjects are not objects that acts like arrays
    ArrayObjects are objects that acts like arrays

    View Slide

  120. 76
    1 $a = array("foo", "bar");
    2 $b = $a;
    3 $b[] = "baz";
    4
    5 print_r ($a);
    6 print_r ($b);

    View Slide

  121. 76
    1 $a = array("foo", "bar");
    2 $b = $a;
    3 $b[] = "baz";
    4
    5 print_r ($a);
    6 print_r ($b);
    Array
    (
    [0] => foo
    [1] => bar
    )
    Array
    (
    [0] => foo
    [1] => bar
    [2] => baz
    )

    View Slide

  122. 77
    1 $a = new ArrayObject();
    2 $a[] = "foo";
    3 $a[] = "bar";
    4
    5 $b = $a;
    6 $b[] = "baz";
    7
    8 print_r (iterator_to_array($a));
    9 print_r (iterator_to_array($b));

    View Slide

  123. 77
    1 $a = new ArrayObject();
    2 $a[] = "foo";
    3 $a[] = "bar";
    4
    5 $b = $a;
    6 $b[] = "baz";
    7
    8 print_r (iterator_to_array($a));
    9 print_r (iterator_to_array($b));
    Array
    (
    [0] => foo
    [1] => bar
    [2] => baz
    )
    Array
    (
    [0] => foo
    [1] => bar
    [2] => baz
    )

    View Slide

  124. 78
    How can we make using the SPL easier?
    http://noscope.com/photostream/albums/various/I_Want_To_Believe_01.jpg

    View Slide

  125. 79
    ➡ The (first and only)
    book about the SPL.
    ➡ Written by me (so you
    know it’s good :P)
    ➡ Fixes the
    documentation problem
    of the SPL (or a wobbly
    table)

    View Slide

  126. 80

    View Slide

  127. ➡ Adaption of the SPL will only happen
    when developers can become familiar
    with it.
    80

    View Slide

  128. ➡ Adaption of the SPL will only happen
    when developers can become familiar
    with it.
    ➡ There is currently no real way to
    familiarize yourself with the SPL.
    80

    View Slide

  129. ➡ BLOG!
    ➡ Update documentation.
    ➡ Find the quirks (and maybe even solve
    them).
    81

    View Slide

  130. http://farm1.static.flickr.com/73/163450213_18478d3aa6_d.jpg 82

    View Slide

  131. 83
    Find me on twitter: @jaytaph
    Find me for development and training: www.noxlogic.nl
    Find me on email: [email protected]
    Find me for blogs: www.adayinthelifeof.nl

    View Slide