SlideShare a Scribd company logo
1 of 50
Download to read offline
Using SPL Tools in Your Code

  OTHERWISE KNOWN AS SPL IN THE WILD
If you don’t know what
SPL is or have never
used SPL features, this
talk might go fast for
you.

Feedback is good!
Why SPL?
What SPL?         tandard HP ibrary
How SPL?    A library of standard interfaces,
             classes, and functions designed
             to solve common programming
                problems and allow engine
                       overloading
But isn’t SPL an Extension?

—  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 6 years ago)
—  As of 5.3, SPL cannot be turned off


 If you don’t have SPL, whoever built your PHP is an
                         idiot.
Autoload

DON’T LET FRIENDS USE __AUTOLOAD
Autoload Stack err Queue

—  spl_autoload_register()
—  spl_autoload_unregister()
—  spl_autoload_call()
—  spl_autoload_functions()




—  https://github.com/hyla/hyla/blob/
 a9f445115b942865241653dce02aa029c7453f41/
 kohana/application/bootstrap.php
Beware the Weirdness

—  spl_autoload()
    ¡  lowercase

    ¡  relative paths

    ¡  namespace aware

—  spl_autoload_extensions()
    ¡  include the .

    ¡  no spaces in between

    ¡  comma separated string
Exceptions

WHAT WENT WRONG WHERE
Exception Classes



                  LogicException
BadFunctionCall     Domain     InvalidArgument    Length     OutofRange
   Exception       Exception      Exception      Exception    Exception




BadMethodCall
  Exception
Exception Classes



                    RuntimeException




                                                  Unexpected
OutofBounds   Overflow     Range      Underflow      Value
 Exception    Exception   Exception   Exception
                                                   Exception
Marker Interface

—  Note that the ability to “nest” exceptions in 5.3
    makes using this stuff far more practical
—  Component level interface as the “marker” or
    “domain” for all exceptions belonging to a library or
    package
—  Specific types of exceptions for code that tell what
    happened
Arrays as Objects

I’M AN ARRAY, WELL KIND OF BUT
     I’M AN OBJECT, REALLY!
    I AM INCREDIBLY USEFUL
The use cases are infinite

—  https://github.com/ooyes/Microweber/blob/
  d4d64cb563b73fa47db5e1e61f913d426d29154c/
  system/application/stats/libs/Zend/Registry.php

—  Gotchas:
    ¡  &offsetGet

    ¡  Quite buggy in 5.2, much more stable in 5.3

    ¡  Can’t use all array functions

    ¡  Serialize, unserialize, sleep, wakeup issues
ArrayAccess, ArrayObject, Array

—  Lots of people want arrayaccess or arrayobject to
    work like an array
—  ArrayObject might be feasible and in fact some of
    these can already be used
—  What about sorting? Merging? Other behavior
Files

YES PHP HAS A FILE OBJECT
 WELL ACTUALLY IT HAS 3
      SPLFILEINFO
     SPLFILEOBJECT
   SPLTEMPFILEOBJECT
Practical Uses

—  https://github.com/fqqdk/phpcmc/blob/
 c3b2450ff6f0293f3de0525745f4f5d551181d0d/src/
 jabbar/PearXmlBuilder.php

—  https://github.com/horde/horde/blob/
 a49d5c901d184dd8581ada0829ad33db053fd07b/
 framework/Support/lib/Horde/Support/
 StringStream.php
Interfaces

MAGIC AND ORGANIZATION
PHP Interfaces

—  Traversable
—  Iterator
—  IteratorAggregate
—  ArrayAccess
—  Serializable


—  And in 5.4 JsonSerializable
Countable

—  Interface meaning “you can count me”
—  Can be put on any class
—  Makes count() magical
—  Note this is NOT the same as iterator_count()
Iterator Interfaces

—  Outer Iterator
—  Inner Iterator
—  Seekable Iterator


—  For examples, pay attention to what all the iterator
  classes we’ll talk about implement
SplSubject SplObserver

—  Are you implementing the observer pattern in your
    code?
—  Do you intend to have other people use your code/
    library in some way?
—  Are you implementing something LIKE the observer
    pattern?

—  http://www.a-scripts.com/object-oriented-php/
 2009/02/21/the-observer-pattern/
Iterators

TAKE A DRINK …
Why Iterators?

—  Readable
—  Easy to understand
—  Testable
—  Easy to refactor
—  Consistent usage
—  Easily add functionality
—  Can be extended
—  Can be chained
Meet the Iterator Interface
So how is it different?

$ar= array();                 $it = new Iterator;



—  reset($ar)                —  $it->rewind()
—  !is_null(key($ar))        —  $it->valid()
—  current($ar)              —  $it->key()
—  key($ar)                  —  $it->current()
—  next($ar)                 —  $it->next()
FilterIterator

—  Abstract Class
—  Has one method that must be implemented – accept
    – which should return true or false
—  Highly useful for many types of iteration
—  https://github.com/sebastianbergmann/php-file-
    iterator/blob/master/File/Iterator.php


      FilterIterator   OuterIterator   Iterator   Traversable
IteratorIterator

—  Regular Class
—  Stick in something that implements traversable
—  Instant Iterator
—  https://github.com/mediaslave/phrails/blob/
  6d40d1584c0202668b071c0fd4b53e060b6724c7/
  framework/db/ResultSet.php


      IteratorIterator    OuterIterator   Iterator   Traversable
ArrayIterator

—  Regular Class
—  Iterates an array – OR the public properties of an
    object! (neat trick – dirty trick)
—  https://github.com/codealchemy/ACL/blob/
    d1729ec7c3aee427fb57da9c2f2817503aa507b5/lib/
    CODEAlchemy/Component/ACL/NodeList.php



                                                              ArrayAccess and
  ArrayIterator   SeekableIterator   Iterator   Traversable    Countable too!
RecursiveIteratorIterator

—  Regular Class
—  Like IteratorIterator only recursive to boot


—  https://github.com/Xosofox/propelVendor/blob/
 85986d1ef52167f3044d69be142c72895174bac1/
 propel/config/PropelConfigurationIterator.php


      RecursiveIteratorIterator   OuterIterator   Iterator   Traversable
ParentIterator

—  Regular Class
—  Filter out stuff without children


—  https://github.com/ebihara/php-src/blob/
 b62203bf12ea1c2b63a0de996a236f43b2ac100c/ext/
 phar/phar/directorygraphiterator.inc


      ParentIterator   OuterIterator    Iterator   Traversable
LimitIterator

—  Regular Class
—  Like mysql’s limit – pick your range and offset and
 foreach away!

—  https://github.com/mintao/zf-mini/blob/
 9efff5f8b25383ef2cdf91b0e4301d90965c4fb8/
 Paginator/SerializableLimitIterator.php

      LimitIterator   OuterIterator   Iterator   Traversable
CachingIterator

—  Regular Class
—  Manages another iterator by checking whether it has
    more elements each time using a hasNext() method
—  https://github.com/shimondoodkin/
    node_spreadsheet/blob/
    e16660cebd2b65abba1a8f5db4449285fa4c3cc6/
    orig/Classes/PHPExcel/Worksheet/RowIterator.php

      CachingIterator    OuterIterator   Iterator   Traversable
RecursiveCachingIterator

—  Regular Class
—  Just like caching iterator only – believe it or not –
    recursive!
—  https://github.com/codedor/cakephp_navigation/
    blob/
    121b3f0594ad0e42a873f65d45583c5ca85343c3/
    views/helpers/menu.php
  RecursiveCachingIterator    CachingIterator   OuterIterator   Iterator   Traversable
DirectoryIterator

—  Regular Class
—  Makes going through directories a snap
—  isDot, isFile – I love you


—  https://github.com/quentinhill/curator/blob/
  44ec76ca9c3d749028b5d950ab78c7dc480dee83/
  Curator/Project.php

                            SplFileInfo
      DirectoryIterator                   Iterator   Traversable
                             (extends)
RecursiveDirectoryIterator

—  Regular Class
—  Like, do it again… and again… and again… and…




—  https://github.com/gjarkko/Track-o-Matic/blob/
 ce506e71326805fe24e38b4262328648cad9a50e/
 server/classes/Tools.php

      DirectoryIterator
          (extends)       RecursiveIterator   Iterator   Traversable
RegexIterator

—  Regular Class
—  Filter an iterator by a regex
—  Pick how you want it to match


—  https://github.com/drm/Sprig/blob/
  b57bee029ce3d4317f90f38de2b643e3b6d94c96/lib/
  Sprig/Extension/Smarty/PluginLoader/Iterator.php

       FilterIterator   IteratorIterator
                                           Iterator   Traversable
         (extends)         (extends)
Datastructures

             NEW WAYS OF MANAGING DATA




http://matthewturland.com/2010/05/20/new-spl-features-in-php-5-3/
DoublyLinkedLists – CS Lesson

—  ordered collection of values
—  linked to each element before it
—  linked to each element after it
—  “doubly linked”




—  PHP datastructure – a php object with a
 doublylinkedlist stored inside it
SplDoublyLinkedList

—  Don’t use this
—  Yes, that’s a terrible thing to say – but this is really
    nothing more then a “base class” with little to
    recommend on its own
—  Has a doublylinkedlist from C underneath instead of
    a hashtable – if you know what that means you may
    find a real use for this (I have not)
SplStack

—  Data is in LIFO


—  Anything you need to iterate a lot
—  Even cooler? Turn on the mode that will autodelete each
  item as you process it

—  Any Queue you need to push stuff onto and deal with in
  LIFO order

—  https://github.com/CHH/Spark2/blob/
  a01607a2480bd6a9b8251e56579fe84869683925/lib/
  Spark/App.php
SplQueue

—  Data is in FIFO

—  Anything you need to iterate a lot
—  Even cooler? Turn on the mode that will autodelete each
  item as you process it

—  Any Queue you need to push stuff onto and deal with in
  LIFO order

—  https://github.com/composer/composer/blob/
  52565a593529048a631110879c76b46bbf76ba82/src/
  Composer/DependencyResolver/Solver.php
Heap – CS Lesson

—  comparison function used to compare the new
    element to other elements
—  element is placed according to functions return value
—  underlying algorithm does it with minimal
    comparisons



—  PHP datastructure – a php object with a heap stored
 inside it
Using SplHeap

—  This is an abstract class
—  You need to compare elements




—  https://github.com/ckwalsh/LibSprite
SplMinHeap, SplMaxHeap

—  These are concrete heap implementations, designed
 to grab the lowest possible value out, or the highest
 possible




—  https://github.com/Wordi/LooPHP/blob/
 fce3947bc27cdd4ae2109e62f7ad58ed68af7862/
 LooPHP/EventLoop.php
SplPriorityQueue

—  Uses heap internally
—  Is non-deterministic when identical priorities are
 used (bug bug bug….)




—  https://github.com/ss23/DeBot/blob/
 dced95faaf5b5284057d0824151bae4a95866305/
 core/SplFIFOPriorityQueue.php
SplFixedArray

—  You have a large amount of data, you know the final
    size, you need to stick it into an array
—  You’re not going to expand it past the final size
—  This is not a small amount of data
—  You might need it in non-sequential order but can
    handle having only integers for keys

—  https://github.com/cboden/gClient/blob/
 429b27a54db5b4c1d30bbdc83566678c03b96bea/
 lib/gClient/Calendar/Calendar.php
SplObjectStorage

—  This can be used two ways
    ¡  Objects can be keys in an array (with two values)

    ¡  As a Set (with one value)




—  https://github.com/greggles/
  epm_project_management/blob/
  50b904333647216ec678fd922f4ac53dbf0e53ee/
  QueryPath/CssEventHandler.php
What do you want to see in SPL?


—  More standard interface?
—  More datastructures?
    ¡  trees?

    ¡  graphs?

—  More iterators? really? more?
Get Involved

—  http://edit.php.net
—  Blog posts
—  Articles
—  Use SPL in the wild
Contact Me

—  http://emsmith.net
—  http://joind.in/3791
—  auroraeosrose@gmail.com
—  IRC – freenode – auroraeosrose
—  #php-gtk #coapp and others

More Related Content

What's hot

Effective Scala (SoftShake 2013)
Effective Scala (SoftShake 2013)Effective Scala (SoftShake 2013)
Effective Scala (SoftShake 2013)
mircodotta
 
Benchmarking the Efficiency of Your Tools
Benchmarking the Efficiency of Your ToolsBenchmarking the Efficiency of Your Tools
Benchmarking the Efficiency of Your Tools
Marian Marinov
 

What's hot (20)

C++ boot camp part 1/2
C++ boot camp part 1/2C++ boot camp part 1/2
C++ boot camp part 1/2
 
Reading Other Peoples Code (Web Rebels 2018)
Reading Other Peoples Code (Web Rebels 2018)Reading Other Peoples Code (Web Rebels 2018)
Reading Other Peoples Code (Web Rebels 2018)
 
Metaprogramação em Python: Decorators e Metaclasses
Metaprogramação em Python: Decorators e MetaclassesMetaprogramação em Python: Decorators e Metaclasses
Metaprogramação em Python: Decorators e Metaclasses
 
Ida python intro
Ida python introIda python intro
Ida python intro
 
Python - Introduction
Python - IntroductionPython - Introduction
Python - Introduction
 
Learning Python from Data
Learning Python from DataLearning Python from Data
Learning Python from Data
 
__proto__-and-prototype
  __proto__-and-prototype  __proto__-and-prototype
__proto__-and-prototype
 
Write code that writes code!
Write code that writes code!Write code that writes code!
Write code that writes code!
 
Effective Scala (SoftShake 2013)
Effective Scala (SoftShake 2013)Effective Scala (SoftShake 2013)
Effective Scala (SoftShake 2013)
 
Learn To Test Like A Grumpy Programmer - 3 hour workshop
Learn To Test Like A Grumpy Programmer - 3 hour workshopLearn To Test Like A Grumpy Programmer - 3 hour workshop
Learn To Test Like A Grumpy Programmer - 3 hour workshop
 
Introduction to Writing Readable and Maintainable Perl (YAPC::EU 2011 Version)
Introduction to Writing Readable and Maintainable Perl (YAPC::EU 2011 Version)Introduction to Writing Readable and Maintainable Perl (YAPC::EU 2011 Version)
Introduction to Writing Readable and Maintainable Perl (YAPC::EU 2011 Version)
 
Code with style
Code with styleCode with style
Code with style
 
Developing A Procedural Language For Postgre Sql
Developing A Procedural Language For Postgre SqlDeveloping A Procedural Language For Postgre Sql
Developing A Procedural Language For Postgre Sql
 
Wait, IPython can do that?
Wait, IPython can do that?Wait, IPython can do that?
Wait, IPython can do that?
 
Benchmarking the Efficiency of Your Tools
Benchmarking the Efficiency of Your ToolsBenchmarking the Efficiency of Your Tools
Benchmarking the Efficiency of Your Tools
 
Wait, IPython can do that?! (30 minutes)
Wait, IPython can do that?! (30 minutes)Wait, IPython can do that?! (30 minutes)
Wait, IPython can do that?! (30 minutes)
 
Joys & frustrations of putting 34,000 lines of Haskell into production (at Va...
Joys & frustrations of putting 34,000 lines of Haskell into production (at Va...Joys & frustrations of putting 34,000 lines of Haskell into production (at Va...
Joys & frustrations of putting 34,000 lines of Haskell into production (at Va...
 
PHP 7 Crash Course - php[world] 2015
PHP 7 Crash Course - php[world] 2015PHP 7 Crash Course - php[world] 2015
PHP 7 Crash Course - php[world] 2015
 
Unit Testing Lots of Perl
Unit Testing Lots of PerlUnit Testing Lots of Perl
Unit Testing Lots of Perl
 
F# and Reactive Programming for iOS
F# and Reactive Programming for iOSF# and Reactive Programming for iOS
F# and Reactive Programming for iOS
 

Similar to Using spl tools in your code

Php Extensions for Dummies
Php Extensions for DummiesPhp Extensions for Dummies
Php Extensions for Dummies
Elizabeth Smith
 

Similar to Using spl tools in your code (20)

Spl in the wild
Spl in the wildSpl in the wild
Spl in the wild
 
Spl to the Rescue - Zendcon 09
Spl to the Rescue - Zendcon 09Spl to the Rescue - Zendcon 09
Spl to the Rescue - Zendcon 09
 
SPL to the Rescue - Tek 09
SPL to the Rescue - Tek 09SPL to the Rescue - Tek 09
SPL to the Rescue - Tek 09
 
Php extensions
Php extensionsPhp extensions
Php extensions
 
JDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go Wrong
JDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go WrongJDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go Wrong
JDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go Wrong
 
Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL Iterators
 
PHP 5
PHP 5PHP 5
PHP 5
 
An Introduction to SPL, the Standard PHP Library
An Introduction to SPL, the Standard PHP LibraryAn Introduction to SPL, the Standard PHP Library
An Introduction to SPL, the Standard PHP Library
 
How to Reverse Engineer Web Applications
How to Reverse Engineer Web ApplicationsHow to Reverse Engineer Web Applications
How to Reverse Engineer Web Applications
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
 
Python and Zope: An introduction (May 2004)
Python and Zope: An introduction (May 2004)Python and Zope: An introduction (May 2004)
Python and Zope: An introduction (May 2004)
 
Sparklife - Life In The Trenches With Spark
Sparklife - Life In The Trenches With SparkSparklife - Life In The Trenches With Spark
Sparklife - Life In The Trenches With Spark
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Patterns in Python
Patterns in PythonPatterns in Python
Patterns in Python
 
PHP7 - A look at the future
PHP7 - A look at the futurePHP7 - A look at the future
PHP7 - A look at the future
 
PHP 7 - A look at the future
PHP 7 - A look at the futurePHP 7 - A look at the future
PHP 7 - A look at the future
 
Php Extensions for Dummies
Php Extensions for DummiesPhp Extensions for Dummies
Php Extensions for Dummies
 
New Stuff In Php 5.3
New Stuff In Php 5.3New Stuff In Php 5.3
New Stuff In Php 5.3
 
PHP 8: What's New and Changed
PHP 8: What's New and ChangedPHP 8: What's New and Changed
PHP 8: What's New and Changed
 
In Vogue Dynamic
In Vogue DynamicIn Vogue Dynamic
In Vogue Dynamic
 

More from Elizabeth Smith

Security is not a feature
Security is not a featureSecurity is not a feature
Security is not a feature
Elizabeth Smith
 
Socket programming with php
Socket programming with phpSocket programming with php
Socket programming with php
Elizabeth Smith
 
Mentoring developers - Zendcon 2012
Mentoring developers - Zendcon 2012Mentoring developers - Zendcon 2012
Mentoring developers - Zendcon 2012
Elizabeth Smith
 
Event and Signal Driven Programming Zendcon 2012
Event and Signal Driven Programming Zendcon 2012Event and Signal Driven Programming Zendcon 2012
Event and Signal Driven Programming Zendcon 2012
Elizabeth Smith
 

More from Elizabeth Smith (20)

Welcome to the internet
Welcome to the internetWelcome to the internet
Welcome to the internet
 
Database theory and modeling
Database theory and modelingDatabase theory and modeling
Database theory and modeling
 
Taming the resource tiger
Taming the resource tigerTaming the resource tiger
Taming the resource tiger
 
Modern sql
Modern sqlModern sql
Modern sql
 
Taming the resource tiger
Taming the resource tigerTaming the resource tiger
Taming the resource tiger
 
Php internal architecture
Php internal architecturePhp internal architecture
Php internal architecture
 
Taming the tiger - pnwphp
Taming the tiger - pnwphpTaming the tiger - pnwphp
Taming the tiger - pnwphp
 
Php extensions
Php extensionsPhp extensions
Php extensions
 
Php’s guts
Php’s gutsPhp’s guts
Php’s guts
 
Lexing and parsing
Lexing and parsingLexing and parsing
Lexing and parsing
 
Hacking with hhvm
Hacking with hhvmHacking with hhvm
Hacking with hhvm
 
Security is not a feature
Security is not a featureSecurity is not a feature
Security is not a feature
 
Using unicode with php
Using unicode with phpUsing unicode with php
Using unicode with php
 
Mentoring developers-php benelux-2014
Mentoring developers-php benelux-2014Mentoring developers-php benelux-2014
Mentoring developers-php benelux-2014
 
Using unicode with php
Using unicode with phpUsing unicode with php
Using unicode with php
 
Socket programming with php
Socket programming with phpSocket programming with php
Socket programming with php
 
Mentoring developers
Mentoring developersMentoring developers
Mentoring developers
 
Do the mentor thing
Do the mentor thingDo the mentor thing
Do the mentor thing
 
Mentoring developers - Zendcon 2012
Mentoring developers - Zendcon 2012Mentoring developers - Zendcon 2012
Mentoring developers - Zendcon 2012
 
Event and Signal Driven Programming Zendcon 2012
Event and Signal Driven Programming Zendcon 2012Event and Signal Driven Programming Zendcon 2012
Event and Signal Driven Programming Zendcon 2012
 

Recently uploaded

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Recently uploaded (20)

AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 

Using spl tools in your code

  • 1. Using SPL Tools in Your Code OTHERWISE KNOWN AS SPL IN THE WILD
  • 2. If you don’t know what SPL is or have never used SPL features, this talk might go fast for you. Feedback is good!
  • 3. Why SPL? What SPL? tandard HP ibrary How SPL? A library of standard interfaces, classes, and functions designed to solve common programming problems and allow engine overloading
  • 4. But isn’t SPL an Extension? —  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 6 years ago) —  As of 5.3, SPL cannot be turned off If you don’t have SPL, whoever built your PHP is an idiot.
  • 6. Autoload Stack err Queue —  spl_autoload_register() —  spl_autoload_unregister() —  spl_autoload_call() —  spl_autoload_functions() —  https://github.com/hyla/hyla/blob/ a9f445115b942865241653dce02aa029c7453f41/ kohana/application/bootstrap.php
  • 7. Beware the Weirdness —  spl_autoload() ¡  lowercase ¡  relative paths ¡  namespace aware —  spl_autoload_extensions() ¡  include the . ¡  no spaces in between ¡  comma separated string
  • 9. Exception Classes LogicException BadFunctionCall Domain InvalidArgument Length OutofRange Exception Exception Exception Exception Exception BadMethodCall Exception
  • 10. Exception Classes RuntimeException Unexpected OutofBounds Overflow Range Underflow Value Exception Exception Exception Exception Exception
  • 11. Marker Interface —  Note that the ability to “nest” exceptions in 5.3 makes using this stuff far more practical —  Component level interface as the “marker” or “domain” for all exceptions belonging to a library or package —  Specific types of exceptions for code that tell what happened
  • 12. Arrays as Objects I’M AN ARRAY, WELL KIND OF BUT I’M AN OBJECT, REALLY! I AM INCREDIBLY USEFUL
  • 13. The use cases are infinite —  https://github.com/ooyes/Microweber/blob/ d4d64cb563b73fa47db5e1e61f913d426d29154c/ system/application/stats/libs/Zend/Registry.php —  Gotchas: ¡  &offsetGet ¡  Quite buggy in 5.2, much more stable in 5.3 ¡  Can’t use all array functions ¡  Serialize, unserialize, sleep, wakeup issues
  • 14. ArrayAccess, ArrayObject, Array —  Lots of people want arrayaccess or arrayobject to work like an array —  ArrayObject might be feasible and in fact some of these can already be used —  What about sorting? Merging? Other behavior
  • 15. Files YES PHP HAS A FILE OBJECT WELL ACTUALLY IT HAS 3 SPLFILEINFO SPLFILEOBJECT SPLTEMPFILEOBJECT
  • 16. Practical Uses —  https://github.com/fqqdk/phpcmc/blob/ c3b2450ff6f0293f3de0525745f4f5d551181d0d/src/ jabbar/PearXmlBuilder.php —  https://github.com/horde/horde/blob/ a49d5c901d184dd8581ada0829ad33db053fd07b/ framework/Support/lib/Horde/Support/ StringStream.php
  • 18. PHP Interfaces —  Traversable —  Iterator —  IteratorAggregate —  ArrayAccess —  Serializable —  And in 5.4 JsonSerializable
  • 19. Countable —  Interface meaning “you can count me” —  Can be put on any class —  Makes count() magical —  Note this is NOT the same as iterator_count()
  • 20. Iterator Interfaces —  Outer Iterator —  Inner Iterator —  Seekable Iterator —  For examples, pay attention to what all the iterator classes we’ll talk about implement
  • 21. SplSubject SplObserver —  Are you implementing the observer pattern in your code? —  Do you intend to have other people use your code/ library in some way? —  Are you implementing something LIKE the observer pattern? —  http://www.a-scripts.com/object-oriented-php/ 2009/02/21/the-observer-pattern/
  • 23. Why Iterators? —  Readable —  Easy to understand —  Testable —  Easy to refactor —  Consistent usage —  Easily add functionality —  Can be extended —  Can be chained
  • 24. Meet the Iterator Interface
  • 25. So how is it different? $ar= array(); $it = new Iterator; —  reset($ar) —  $it->rewind() —  !is_null(key($ar)) —  $it->valid() —  current($ar) —  $it->key() —  key($ar) —  $it->current() —  next($ar) —  $it->next()
  • 26. FilterIterator —  Abstract Class —  Has one method that must be implemented – accept – which should return true or false —  Highly useful for many types of iteration —  https://github.com/sebastianbergmann/php-file- iterator/blob/master/File/Iterator.php FilterIterator OuterIterator Iterator Traversable
  • 27. IteratorIterator —  Regular Class —  Stick in something that implements traversable —  Instant Iterator —  https://github.com/mediaslave/phrails/blob/ 6d40d1584c0202668b071c0fd4b53e060b6724c7/ framework/db/ResultSet.php IteratorIterator OuterIterator Iterator Traversable
  • 28. ArrayIterator —  Regular Class —  Iterates an array – OR the public properties of an object! (neat trick – dirty trick) —  https://github.com/codealchemy/ACL/blob/ d1729ec7c3aee427fb57da9c2f2817503aa507b5/lib/ CODEAlchemy/Component/ACL/NodeList.php ArrayAccess and ArrayIterator SeekableIterator Iterator Traversable Countable too!
  • 29. RecursiveIteratorIterator —  Regular Class —  Like IteratorIterator only recursive to boot —  https://github.com/Xosofox/propelVendor/blob/ 85986d1ef52167f3044d69be142c72895174bac1/ propel/config/PropelConfigurationIterator.php RecursiveIteratorIterator OuterIterator Iterator Traversable
  • 30. ParentIterator —  Regular Class —  Filter out stuff without children —  https://github.com/ebihara/php-src/blob/ b62203bf12ea1c2b63a0de996a236f43b2ac100c/ext/ phar/phar/directorygraphiterator.inc ParentIterator OuterIterator Iterator Traversable
  • 31. LimitIterator —  Regular Class —  Like mysql’s limit – pick your range and offset and foreach away! —  https://github.com/mintao/zf-mini/blob/ 9efff5f8b25383ef2cdf91b0e4301d90965c4fb8/ Paginator/SerializableLimitIterator.php LimitIterator OuterIterator Iterator Traversable
  • 32. CachingIterator —  Regular Class —  Manages another iterator by checking whether it has more elements each time using a hasNext() method —  https://github.com/shimondoodkin/ node_spreadsheet/blob/ e16660cebd2b65abba1a8f5db4449285fa4c3cc6/ orig/Classes/PHPExcel/Worksheet/RowIterator.php CachingIterator OuterIterator Iterator Traversable
  • 33. RecursiveCachingIterator —  Regular Class —  Just like caching iterator only – believe it or not – recursive! —  https://github.com/codedor/cakephp_navigation/ blob/ 121b3f0594ad0e42a873f65d45583c5ca85343c3/ views/helpers/menu.php RecursiveCachingIterator CachingIterator OuterIterator Iterator Traversable
  • 34. DirectoryIterator —  Regular Class —  Makes going through directories a snap —  isDot, isFile – I love you —  https://github.com/quentinhill/curator/blob/ 44ec76ca9c3d749028b5d950ab78c7dc480dee83/ Curator/Project.php SplFileInfo DirectoryIterator Iterator Traversable (extends)
  • 35. RecursiveDirectoryIterator —  Regular Class —  Like, do it again… and again… and again… and… —  https://github.com/gjarkko/Track-o-Matic/blob/ ce506e71326805fe24e38b4262328648cad9a50e/ server/classes/Tools.php DirectoryIterator (extends) RecursiveIterator Iterator Traversable
  • 36. RegexIterator —  Regular Class —  Filter an iterator by a regex —  Pick how you want it to match —  https://github.com/drm/Sprig/blob/ b57bee029ce3d4317f90f38de2b643e3b6d94c96/lib/ Sprig/Extension/Smarty/PluginLoader/Iterator.php FilterIterator IteratorIterator Iterator Traversable (extends) (extends)
  • 37. Datastructures NEW WAYS OF MANAGING DATA http://matthewturland.com/2010/05/20/new-spl-features-in-php-5-3/
  • 38. DoublyLinkedLists – CS Lesson —  ordered collection of values —  linked to each element before it —  linked to each element after it —  “doubly linked” —  PHP datastructure – a php object with a doublylinkedlist stored inside it
  • 39. SplDoublyLinkedList —  Don’t use this —  Yes, that’s a terrible thing to say – but this is really nothing more then a “base class” with little to recommend on its own —  Has a doublylinkedlist from C underneath instead of a hashtable – if you know what that means you may find a real use for this (I have not)
  • 40. SplStack —  Data is in LIFO —  Anything you need to iterate a lot —  Even cooler? Turn on the mode that will autodelete each item as you process it —  Any Queue you need to push stuff onto and deal with in LIFO order —  https://github.com/CHH/Spark2/blob/ a01607a2480bd6a9b8251e56579fe84869683925/lib/ Spark/App.php
  • 41. SplQueue —  Data is in FIFO —  Anything you need to iterate a lot —  Even cooler? Turn on the mode that will autodelete each item as you process it —  Any Queue you need to push stuff onto and deal with in LIFO order —  https://github.com/composer/composer/blob/ 52565a593529048a631110879c76b46bbf76ba82/src/ Composer/DependencyResolver/Solver.php
  • 42. Heap – CS Lesson —  comparison function used to compare the new element to other elements —  element is placed according to functions return value —  underlying algorithm does it with minimal comparisons —  PHP datastructure – a php object with a heap stored inside it
  • 43. Using SplHeap —  This is an abstract class —  You need to compare elements —  https://github.com/ckwalsh/LibSprite
  • 44. SplMinHeap, SplMaxHeap —  These are concrete heap implementations, designed to grab the lowest possible value out, or the highest possible —  https://github.com/Wordi/LooPHP/blob/ fce3947bc27cdd4ae2109e62f7ad58ed68af7862/ LooPHP/EventLoop.php
  • 45. SplPriorityQueue —  Uses heap internally —  Is non-deterministic when identical priorities are used (bug bug bug….) —  https://github.com/ss23/DeBot/blob/ dced95faaf5b5284057d0824151bae4a95866305/ core/SplFIFOPriorityQueue.php
  • 46. SplFixedArray —  You have a large amount of data, you know the final size, you need to stick it into an array —  You’re not going to expand it past the final size —  This is not a small amount of data —  You might need it in non-sequential order but can handle having only integers for keys —  https://github.com/cboden/gClient/blob/ 429b27a54db5b4c1d30bbdc83566678c03b96bea/ lib/gClient/Calendar/Calendar.php
  • 47. SplObjectStorage —  This can be used two ways ¡  Objects can be keys in an array (with two values) ¡  As a Set (with one value) —  https://github.com/greggles/ epm_project_management/blob/ 50b904333647216ec678fd922f4ac53dbf0e53ee/ QueryPath/CssEventHandler.php
  • 48. What do you want to see in SPL? —  More standard interface? —  More datastructures? ¡  trees? ¡  graphs? —  More iterators? really? more?
  • 49. Get Involved —  http://edit.php.net —  Blog posts —  Articles —  Use SPL in the wild
  • 50. Contact Me —  http://emsmith.net —  http://joind.in/3791 —  auroraeosrose@gmail.com —  IRC – freenode – auroraeosrose —  #php-gtk #coapp and others