SlideShare a Scribd company logo
1 of 55
Download to read offline
Standard Tools for Everyday Programming
Community Heckling
 On twitter #tek09 (or #phptek) and #spldg
 DG’s for drinking game (you’ll see why later)
 IRC is open, I can see backlog – constructive criticism
 is good

 Comment on http://joind.in/talk/view/186
 No comments on hair, clothes, or my fat belly –
 constructive criticism is welcome ;)
I have a Problem
Recursively iterate through
 directories
Find all .jpg files
Check last modified dates
Moved the ones older than two
 years to new location
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


I think I’m going to need a lot of code….
SPL to the Rescue!
             RecursiveDirectoryIterator
             RecursiveIteratorIterator
             FilterIterator
             SplFileInfo


                  What fun tools we have!
And not the kind you kick out of IRC
What is SPL?
       tandard HP ibrary

  A library of standard interfaces,
 classes, and functions designed to
    solve common programming
     problems and allow engine
            overloading.
That’s nice… in English please.
What is SPL?
1.   Engine overloading hooks via interfaces
        ArrayAccess, Countable, SeekableIterator

2.   Classes that utilize the interfaces do cool things
        ArrayObject, RecursiveIterator, DirectoryIterator

3.   Standard Class Implementations
        Exceptions, SplObserver and SplStorage

4. Functions to help with autoloading and objects
    spl_autoload_register(), spl_classes(), iterator_apply()
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
    source

If you don’t have SPL, whoever built your PHP is an idiot
(or an evil genius – it’s HARD).
Helper functions from SPL to you
Autoload Magic
 spl_autoload() – default autoload implementation
 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_extensions() – ext for spl_autoload()
 spl_autoload_call() – load something through the
 stack
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
Object Helper Functions
 class_implements()
 class_parents()
 spl_object_hash()




Why are these not in core?
I DON’T KNOW - GO ASK YOUR DAD!
Nothing but Templates
Exception Classes
                                     LogicException




BadFunctionCallE                     InvalidArgumentE                     OutofRangeExcept
                   DomainException                      LengthException
    xception                              xception                              ion




 BadMethodCall
Exception Classes

                                     RuntimeException




OutofBoundsExce   OverflowExceptio                      UnderflowExcepti   UnexpectedValueE
                                      RangeException
     ption               n                                     on              xception
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 what kind they
  are
 Do I recommend it? Depends on how exceptions are
  used in your application.
Foreach is your bestest friend! Foreach an object today!
The iterator drinking game!
 Every time someone says the word iterator tonight,
  take a drink
 Start a conversation with me, and you’ll be gone in
  about five minutes

  It’s the SPL drinking game (tonight at cocktail hour)
Iterators
 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.
 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?
Foreach it baby!
 Foreach is your friend
 iterators give your code consistent usage
 and you can add more functionality


 What else can you do with iterators?
   Extend Iterators to do what you need
   Chain Iterators: iteratoriteratoriteratoriterator


(that’s 5 shots)….
Meet the Iterator Interface
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()
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
See, the drinking game will be lots of fun….
Innie or an Outie?
          OuterIterator (interface)
            Extends Iterator
            Puts a wrapper around an iterator
             inside
            Has one additional method –
             getInnerIterator() that should be
             implemented
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
Jumping ahead?
                  SeekableIterator
                  (interface)
                    Additional method –
                     seek(string $position)
                    Lets you jump to a
                     specific spot to start
                     iterating
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 classes


Choose Wisely
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
IteratorIterator
 Regular Class
 Iterates an iterator – No I am not kidding




     IteratorIterator   OuterIterator   Iterator   Traversable
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!
RecursiveIteratorIterator
 Regular Class
 Like IteratorIterator only recursive to boot – still not
  kidding - but I don’t say it as cool as Marcus




     RecursiveIteratorIterator   OuterIterator   Iterator   Traversable
ParentIterator
 Regular Class
 Filter out stuff without children




     ParentIterator   OuterIterator   Iterator   Traversable
LimitIterator
 Regular Class
 Like mysql’s limit – pick your range and offset and
 foreach away!




     LimitIterator   OuterIterator   Iterator    Traversable
CachingIterator
 Regular Class
 Manages another iterator by checking whether it has
 more elements each time using a hasNext() method




     CachingIterator   OuterIterator   Iterator   Traversable
RecursiveCachingIterator
 Regular Class
 Just like caching iterator only – believe it or not –
  recursive!




 RecursiveCachingIterator   CachingIterator   OuterIterator   Iterator   Traversable
DirectoryIterator
 Regular Class
 Makes going through directories a snap
 isDot, isFile – I love you




                         SplFileInfo
     DirectoryIterator                 Iterator   Traversable
                          (extends)
RecursiveDirectoryIterator
 Regular Class
 Like, do it again… and again… and again… and…




     DirectoryIterator
                         RecursiveIterator   Iterator   Traversable
        (extends)
Iterator Helper Functions
 iterator_apply() – like array_walk for your iterator
  implementing objects
 iterator_count() – count the items in your iterator (not
  quite the same as implementing countable::count)
 iterator_to_array() – copy all the stuff from your
  iterator into a regular PHP array

Even Superman
doesn’t work alone
Is it an array? An object? Why… it’s both!
ArrayAccess Interface
ArrayObject
 A class, NOT an interface
 It’s like arrayaccess on RedBull
 The manual LIES – for a full list of everything you can
  do with arrayobject, see
  http://www.php.net/~helly/php/ext/spl/
 Highlights
   exchangeArray
   getArrayCopy (get your internally stored array)
   Sorting methods
     ksort et al
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
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
SPLFixedArray
 A fixed length, int key only array
 Why? It’s FAST (very fast) because it stores data
  differently “under the hood” in C
 Regular class, don’t need to extend and fill in any
  methods
 5.3+
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
SplFileInfo
 fancy class for a file
 all the file system functions in compact object form
    getMTime == filemtime
    openFile == fopen
Beyond arrays to the wild wild west
New and Shiny

         SplDoublyLinkedList




   SplStack              SplQueue
More Data Structures

              SplHeap         SplPriorityQueue




 SplMaxHeap             SplMinHeap
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!
Resources
 http://php.net/spl - spl docs
 http://php.net/~helly/php/ext/spl - Doxygen docs
 http://blueparabola.com/blog/spl-deserves-some-
 reiteration - some stuff about new data structures

 auroraeosrose@php.net

More Related Content

What's hot

Understanding PHP objects
Understanding PHP objectsUnderstanding PHP objects
Understanding PHP objectsjulien pauli
 
Programming in Computational Biology
Programming in Computational BiologyProgramming in Computational Biology
Programming in Computational BiologyAtreyiB
 
Doing It Wrong with Puppet -
Doing It Wrong with Puppet - Doing It Wrong with Puppet -
Doing It Wrong with Puppet - Puppet
 
Zephir - A Wind of Change for writing PHP extensions
Zephir - A Wind of Change for writing PHP extensionsZephir - A Wind of Change for writing PHP extensions
Zephir - A Wind of Change for writing PHP extensionsMark Baker
 
PHP 8.1 - What's new and changed
PHP 8.1 - What's new and changedPHP 8.1 - What's new and changed
PHP 8.1 - What's new and changedAyesh Karunaratne
 
MIND sweeping introduction to PHP
MIND sweeping introduction to PHPMIND sweeping introduction to PHP
MIND sweeping introduction to PHPBUDNET
 
Doing the Refactor Dance - Making Your Puppet Modules More Modular - PuppetCo...
Doing the Refactor Dance - Making Your Puppet Modules More Modular - PuppetCo...Doing the Refactor Dance - Making Your Puppet Modules More Modular - PuppetCo...
Doing the Refactor Dance - Making Your Puppet Modules More Modular - PuppetCo...Puppet
 
Yapc::NA::2009 - Command Line Perl
Yapc::NA::2009 - Command Line PerlYapc::NA::2009 - Command Line Perl
Yapc::NA::2009 - Command Line PerlBruce Gray
 
PHP 良好實踐 (Best Practice)
PHP 良好實踐 (Best Practice)PHP 良好實踐 (Best Practice)
PHP 良好實踐 (Best Practice)Win Yu
 
Puppet Camp Berlin 2014: Manageable puppet infrastructure
Puppet Camp Berlin 2014: Manageable puppet infrastructurePuppet Camp Berlin 2014: Manageable puppet infrastructure
Puppet Camp Berlin 2014: Manageable puppet infrastructurePuppet
 

What's hot (20)

Cross platform php
Cross platform phpCross platform php
Cross platform php
 
Understanding PHP objects
Understanding PHP objectsUnderstanding PHP objects
Understanding PHP objects
 
IO Streams, Files and Directories
IO Streams, Files and DirectoriesIO Streams, Files and Directories
IO Streams, Files and Directories
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Power of Puppet 4
Power of Puppet 4Power of Puppet 4
Power of Puppet 4
 
Programming in Computational Biology
Programming in Computational BiologyProgramming in Computational Biology
Programming in Computational Biology
 
Anatomy of a reusable module
Anatomy of a reusable moduleAnatomy of a reusable module
Anatomy of a reusable module
 
Doing It Wrong with Puppet -
Doing It Wrong with Puppet - Doing It Wrong with Puppet -
Doing It Wrong with Puppet -
 
Zephir - A Wind of Change for writing PHP extensions
Zephir - A Wind of Change for writing PHP extensionsZephir - A Wind of Change for writing PHP extensions
Zephir - A Wind of Change for writing PHP extensions
 
PHP 8.1 - What's new and changed
PHP 8.1 - What's new and changedPHP 8.1 - What's new and changed
PHP 8.1 - What's new and changed
 
rtwerewr
rtwerewrrtwerewr
rtwerewr
 
Ant
Ant Ant
Ant
 
MIND sweeping introduction to PHP
MIND sweeping introduction to PHPMIND sweeping introduction to PHP
MIND sweeping introduction to PHP
 
Doing the Refactor Dance - Making Your Puppet Modules More Modular - PuppetCo...
Doing the Refactor Dance - Making Your Puppet Modules More Modular - PuppetCo...Doing the Refactor Dance - Making Your Puppet Modules More Modular - PuppetCo...
Doing the Refactor Dance - Making Your Puppet Modules More Modular - PuppetCo...
 
Introduction to Perl and BioPerl
Introduction to Perl and BioPerlIntroduction to Perl and BioPerl
Introduction to Perl and BioPerl
 
Hacking with hhvm
Hacking with hhvmHacking with hhvm
Hacking with hhvm
 
Yapc::NA::2009 - Command Line Perl
Yapc::NA::2009 - Command Line PerlYapc::NA::2009 - Command Line Perl
Yapc::NA::2009 - Command Line Perl
 
PHP 良好實踐 (Best Practice)
PHP 良好實踐 (Best Practice)PHP 良好實踐 (Best Practice)
PHP 良好實踐 (Best Practice)
 
05php
05php05php
05php
 
Puppet Camp Berlin 2014: Manageable puppet infrastructure
Puppet Camp Berlin 2014: Manageable puppet infrastructurePuppet Camp Berlin 2014: Manageable puppet infrastructure
Puppet Camp Berlin 2014: Manageable puppet infrastructure
 

Similar to Standard Tools for Everyday Programming with SPL

Using spl tools in your code
Using spl tools in your codeUsing spl tools in your code
Using spl tools in your codeElizabeth Smith
 
Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsMark Baker
 
Spl in the wild - zendcon2012
Spl in the wild - zendcon2012Spl in the wild - zendcon2012
Spl in the wild - zendcon2012Elizabeth Smith
 
Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsMark Baker
 
Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)mircodotta
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?Nikita Popov
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Fwdays
 
Elegant Solutions For Everyday Python Problems - Nina Zakharenko
Elegant Solutions For Everyday Python Problems - Nina ZakharenkoElegant Solutions For Everyday Python Problems - Nina Zakharenko
Elegant Solutions For Everyday Python Problems - Nina ZakharenkoNina Zakharenko
 
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 LibraryRobin Fernandes
 
Php Extensions for Dummies
Php Extensions for DummiesPhp Extensions for Dummies
Php Extensions for DummiesElizabeth Smith
 
Iterarators and generators in python
Iterarators and generators in pythonIterarators and generators in python
Iterarators and generators in pythonSarfaraz Ghanta
 
Python iteration
Python iterationPython iteration
Python iterationdietbuddha
 
Compiler2016 by abcdabcd987
Compiler2016 by abcdabcd987Compiler2016 by abcdabcd987
Compiler2016 by abcdabcd987乐群 陈
 
JS Fest 2018. Douglas Crockford. The Better Parts
JS Fest 2018. Douglas Crockford. The Better PartsJS Fest 2018. Douglas Crockford. The Better Parts
JS Fest 2018. Douglas Crockford. The Better PartsJSFestUA
 
CakePHP 2.0 - It'll rock your world
CakePHP 2.0 - It'll rock your worldCakePHP 2.0 - It'll rock your world
CakePHP 2.0 - It'll rock your worldGraham Weldon
 
Elegant Solutions For Everyday Python Problems - PyCon Canada 2017
Elegant Solutions For Everyday Python Problems - PyCon Canada 2017Elegant Solutions For Everyday Python Problems - PyCon Canada 2017
Elegant Solutions For Everyday Python Problems - PyCon Canada 2017Nina Zakharenko
 
Code transformation With Spoon
Code transformation With SpoonCode transformation With Spoon
Code transformation With SpoonGérard Paligot
 

Similar to Standard Tools for Everyday Programming with SPL (20)

Using spl tools in your code
Using spl tools in your codeUsing spl tools in your code
Using spl tools in your code
 
Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL Iterators
 
Spl in the wild - zendcon2012
Spl in the wild - zendcon2012Spl in the wild - zendcon2012
Spl in the wild - zendcon2012
 
Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL Iterators
 
Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)
 
Dynamic Python
Dynamic PythonDynamic Python
Dynamic Python
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"
 
Elegant Solutions For Everyday Python Problems - Nina Zakharenko
Elegant Solutions For Everyday Python Problems - Nina ZakharenkoElegant Solutions For Everyday Python Problems - Nina Zakharenko
Elegant Solutions For Everyday Python Problems - Nina Zakharenko
 
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
 
Php Extensions for Dummies
Php Extensions for DummiesPhp Extensions for Dummies
Php Extensions for Dummies
 
Iterarators and generators in python
Iterarators and generators in pythonIterarators and generators in python
Iterarators and generators in python
 
PHP7: Hello World!
PHP7: Hello World!PHP7: Hello World!
PHP7: Hello World!
 
Python iteration
Python iterationPython iteration
Python iteration
 
Compiler2016 by abcdabcd987
Compiler2016 by abcdabcd987Compiler2016 by abcdabcd987
Compiler2016 by abcdabcd987
 
JS Fest 2018. Douglas Crockford. The Better Parts
JS Fest 2018. Douglas Crockford. The Better PartsJS Fest 2018. Douglas Crockford. The Better Parts
JS Fest 2018. Douglas Crockford. The Better Parts
 
CakePHP 2.0 - It'll rock your world
CakePHP 2.0 - It'll rock your worldCakePHP 2.0 - It'll rock your world
CakePHP 2.0 - It'll rock your world
 
Elegant Solutions For Everyday Python Problems - PyCon Canada 2017
Elegant Solutions For Everyday Python Problems - PyCon Canada 2017Elegant Solutions For Everyday Python Problems - PyCon Canada 2017
Elegant Solutions For Everyday Python Problems - PyCon Canada 2017
 
Code transformation With Spoon
Code transformation With SpoonCode transformation With Spoon
Code transformation With Spoon
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 

More from 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
 
Php extensions
Php extensionsPhp extensions
Php extensions
 
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 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
 
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
 

Recently uploaded

Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 

Recently uploaded (20)

Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 

Standard Tools for Everyday Programming with SPL

  • 1. Standard Tools for Everyday Programming
  • 2. Community Heckling  On twitter #tek09 (or #phptek) and #spldg  DG’s for drinking game (you’ll see why later)  IRC is open, I can see backlog – constructive criticism is good  Comment on http://joind.in/talk/view/186  No comments on hair, clothes, or my fat belly – constructive criticism is welcome ;)
  • 3. I have a Problem Recursively iterate through directories Find all .jpg files Check last modified dates Moved the ones older than two years to new location
  • 4. 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 I think I’m going to need a lot of code….
  • 5.
  • 6. SPL to the Rescue!  RecursiveDirectoryIterator  RecursiveIteratorIterator  FilterIterator  SplFileInfo What fun tools we have!
  • 7.
  • 8. And not the kind you kick out of IRC
  • 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. That’s nice… in English please. What is SPL? 1. Engine overloading hooks via interfaces  ArrayAccess, Countable, SeekableIterator 2. Classes that utilize the interfaces do cool things  ArrayObject, RecursiveIterator, DirectoryIterator 3. Standard Class Implementations  Exceptions, SplObserver and SplStorage 4. Functions to help with autoloading and objects  spl_autoload_register(), spl_classes(), iterator_apply()
  • 11. 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 source If you don’t have SPL, whoever built your PHP is an idiot (or an evil genius – it’s HARD).
  • 12. Helper functions from SPL to you
  • 13. Autoload Magic  spl_autoload() – default autoload implementation  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_extensions() – ext for spl_autoload()  spl_autoload_call() – load something through the stack
  • 14. 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
  • 15. Object Helper Functions  class_implements()  class_parents()  spl_object_hash() Why are these not in core? I DON’T KNOW - GO ASK YOUR DAD!
  • 17. Exception Classes LogicException BadFunctionCallE InvalidArgumentE OutofRangeExcept DomainException LengthException xception xception ion BadMethodCall
  • 18. Exception Classes RuntimeException OutofBoundsExce OverflowExceptio UnderflowExcepti UnexpectedValueE RangeException ption n on xception
  • 19. 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 what kind they are  Do I recommend it? Depends on how exceptions are used in your application.
  • 20. Foreach is your bestest friend! Foreach an object today!
  • 21. The iterator drinking game!  Every time someone says the word iterator tonight, take a drink  Start a conversation with me, and you’ll be gone in about five minutes It’s the SPL drinking game (tonight at cocktail hour)
  • 22. Iterators  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.  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?
  • 23. Foreach it baby!  Foreach is your friend  iterators give your code consistent usage  and you can add more functionality  What else can you do with iterators?  Extend Iterators to do what you need  Chain Iterators: iteratoriteratoriteratoriterator (that’s 5 shots)….
  • 24. Meet the Iterator Interface
  • 25. 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()
  • 26. 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
  • 27. See, the drinking game will be lots of fun….
  • 28. Innie or an Outie?  OuterIterator (interface)  Extends Iterator  Puts a wrapper around an iterator inside  Has one additional method – getInnerIterator() that should be implemented
  • 29. 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
  • 30. Jumping ahead?  SeekableIterator (interface)  Additional method – seek(string $position)  Lets you jump to a specific spot to start iterating
  • 31. 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 classes Choose Wisely
  • 32. 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
  • 33. IteratorIterator  Regular Class  Iterates an iterator – No I am not kidding IteratorIterator OuterIterator Iterator Traversable
  • 34. 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!
  • 35. RecursiveIteratorIterator  Regular Class  Like IteratorIterator only recursive to boot – still not kidding - but I don’t say it as cool as Marcus RecursiveIteratorIterator OuterIterator Iterator Traversable
  • 36. ParentIterator  Regular Class  Filter out stuff without children ParentIterator OuterIterator Iterator Traversable
  • 37. LimitIterator  Regular Class  Like mysql’s limit – pick your range and offset and foreach away! LimitIterator OuterIterator Iterator Traversable
  • 38. CachingIterator  Regular Class  Manages another iterator by checking whether it has more elements each time using a hasNext() method CachingIterator OuterIterator Iterator Traversable
  • 39. RecursiveCachingIterator  Regular Class  Just like caching iterator only – believe it or not – recursive! RecursiveCachingIterator CachingIterator OuterIterator Iterator Traversable
  • 40. DirectoryIterator  Regular Class  Makes going through directories a snap  isDot, isFile – I love you SplFileInfo DirectoryIterator Iterator Traversable (extends)
  • 41. RecursiveDirectoryIterator  Regular Class  Like, do it again… and again… and again… and… DirectoryIterator RecursiveIterator Iterator Traversable (extends)
  • 42. Iterator Helper Functions  iterator_apply() – like array_walk for your iterator implementing objects  iterator_count() – count the items in your iterator (not quite the same as implementing countable::count)  iterator_to_array() – copy all the stuff from your iterator into a regular PHP array Even Superman doesn’t work alone
  • 43. Is it an array? An object? Why… it’s both!
  • 45. ArrayObject  A class, NOT an interface  It’s like arrayaccess on RedBull  The manual LIES – for a full list of everything you can do with arrayobject, see http://www.php.net/~helly/php/ext/spl/  Highlights  exchangeArray  getArrayCopy (get your internally stored array)  Sorting methods  ksort et al
  • 46. 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
  • 47. 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
  • 48. SPLFixedArray  A fixed length, int key only array  Why? It’s FAST (very fast) because it stores data differently “under the hood” in C  Regular class, don’t need to extend and fill in any methods  5.3+
  • 49. 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
  • 50. SplFileInfo  fancy class for a file  all the file system functions in compact object form  getMTime == filemtime  openFile == fopen
  • 51. Beyond arrays to the wild wild west
  • 52. New and Shiny SplDoublyLinkedList SplStack SplQueue
  • 53. More Data Structures SplHeap SplPriorityQueue SplMaxHeap SplMinHeap
  • 54. 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!
  • 55. Resources  http://php.net/spl - spl docs  http://php.net/~helly/php/ext/spl - Doxygen docs  http://blueparabola.com/blog/spl-deserves-some- reiteration - some stuff about new data structures  auroraeosrose@php.net