SlideShare a Scribd company logo
1 of 62
Download to read offline
New SPL Features in PHP 5.3

       Matthew Turland
            TEK-X
        May 20, 2010
Hi! My name is…

 β€’   Senior Platform Engineer for Synacor, Inc.
 β€’   Former author and TE for php|architect
 β€’   Author of Web Scraping with PHP
 β€’   Past contributor to Zend Framework
 β€’   Lead developer of Phergie
 β€’   ULL alumni with a BS in computer science
And I work for…

 β€’ Provides internet solutions to ISPs, media
   companies, and advertisers
 β€’ International company with offices in Buffalo,
   New York City, Los Angeles, and Amsterdam
 β€’ Clientele includes most of the top 20 cable
   providers in the United States
 β€’ Great company – join us!
What about you?

 β€’   Used the SPL before?
 β€’   Using PHP 5.3?
 β€’   Computer science background?
 β€’   Knowledge of data structures?
Pre-5.3 SPL Features

 β€’ Classes: ArrayObject, SplFileInfo, SplSubject,
   SplObserver, etc.
 β€’ Iterators: RecursiveIteratorIterator,
   FilterIterator, LimitIterator, etc.
 β€’ Interfaces: ArrayAccess, Countable, Iterator,
   IteratorAggregate, etc.
 β€’ Functions: spl_autoload_register,
   iterator_to_array, spl_object_hash, etc.
Containers

 β€œA container is a class, a data structure, or
 an abstract data type whose instances are
 collections of other objects. They are used
 to store objects in an organized way
 following specific access rules.”

 Container (data structure) - Wikipedia
Why containers?

 β€’ We already have arrays and strings!
       array()               'string'
Two excellent reasons

 β€’ Versus traditional arrays, there is potential for:
   – Less CPU usage
   – Less memory usage
Arrays are (not always) great

 β€’ Flexible general purpose container
 β€’ Underlying hash table algorithm is not always
   ideal for the task at hand
Warning: Benchmarks Ahead

 β€’ Lies, Outrageous Lies, and Benchmarks
 β€’ PHP 5.3.2 compiled on Ubuntu 9.10
 β€’ Intel Core2Duo 1.83 GHz, 4 GB DDR2 RAM
 β€’ Performance results are shown in executions
   per second rather than time per execution to
   avoid really small numbers
 β€’ Code and results
The List
SplFixedArray - What

 β€’   Like an array, but with a fixed length
 β€’   Only allows integers >= 0 for keys
 β€’   Can be resized, but at a cost
 β€’   Not compatible with array functions
SplFixedArray - When

 β€’ It’s best to use this when:
   – You know in advance how many elements you
     want to store (e.g. mysql_num_rows)
   – You only need to access elements in sequential
     order
SplFixedArray - Code
    <?php
    $a = array();
    for ($i = 0; $i < $argv[1]; $i++) {
        $a[$i] = $i;
        $i = $a[$i];
    }
    <?php
    $a = new SplFixedArray($argv[1]);
    for ($i = 0; $i < $argv[1]; $i++) {
        $a[$i] = $i;
        $i = $a[$i];
    }
SplFixedArray - EPS
SplFixedArray - Memory
SplDoublyLinkedList - What

 β€’ Mainly intended as a parent class
 β€’ Same unlimited size as arrays without the
   associated hash map algorithm
 β€’ Less performance, but more memory
   efficiency
SplDoublyLinkedList - When

 β€’ It’s best to use this when:
   – You do not know in advance how many elements
     you want to store
   – You only need to access elements in sequential
     order
SplDoublyLinkedList - Code
  <?php
  $a = array();
  for ($i = 0; $i < $argv[1]; $i++) {
      $a[] = $i;
      $i = $a[$i];
  }
  <?php
  $a = new SplDoublyLinkedList($argv[1]);
  for ($i = 0; $i < $argv[1]; $i++) {
      $a[] = $i;
      $i = $a[$i];
  }
SplDoublyLinkedList - EPS
SplDoublyLinkedList - Memory
The Stack
SplStack - What

 β€’ 2 operations
    – Push: [] for both array and SplStack
    – Pop: array_pop() vs SplStack::pop()
 β€’ Last In, First Out (LIFO)
    – The last item pushed onto the top of the stack is
      the first item that will be popped off of the top of
      the stack
SplStack - When

 β€’ It’s best to use this when:
   – You do not know in advance how many elements
     you want to store
   – You only ever need to access the last element you
     stored
SplStack - Code

    <?php
    $a = array();
    for($i = 0; $i < $argv[1]; $i++) {
        $a[] = $i;
    }
    for($i = 0; $i < $argv[1]; $i++) {
        array_pop($a);
    }
SplStack - Code (cont.)

    <?php
    $a = new SplStack;
    for($i = 0; $i < $argv[1]; $i++) {
        $a[] = $i;
    }
    for($i = 0; $i < $argv[1]; $i++) {
        $a->pop();
    }
SplStack - EPS
SplStack - Memory
The Queue
SplQueue - What

 β€’ 2 operations
    – Enqueue: [] for both array and SplQueue
    – Dequeue: array_shift() vs SplQueue::dequeue()
 β€’ First In, First Out (FIFO)
    – The first item added to the end of the queue will
      be the first item removed from the front of the
      queue
SplQueue - When

β€’ It’s best to use this when:
  – You do not know in advance how many elements
    you want to store
  – You only ever need to access the remaining
    element that was stored earliest
SplQueue - Code

    <?php
    $a = array();
    for($i = 0; $i < $argv[1]; $i++) {
        $a[] = $i;
    }
    for($i = 0; $i < $argv[1]; $i++) {
        array_shift($a);
    }
SplQueue - Code (cont.)

    <?php
    $a = new SplQueue;
    for($i = 0; $i < $argv[1]; $i++) {
        $a[] = $i;
    }
    for($i = 0; $i < $argv[1]; $i++) {
        $a->dequeue();
    }
SplQueue - EPS
SplQueue - Memory
The Heap
SplHeap - What
 β€’ 2 operations
   – Insert: [] + sort vs SplHeap::insert()
   – Remove: array_shift() vs SplHeap::extract()
 β€’ Internally reorders items based on comparison
   – SplHeap::compare() can be overridden
 β€’ Subclasses
   – SplMinHeap
   – SplMaxHeap
 β€’ Better worst-case scenario performance
   versus arrays (heap sort versus quick sort)
SplHeap - When

 β€’ It’s best to use this when:
   – You do not know in advance how many elements
     you want to store
   – You need to access elements in an order based on
     how they compare to each other
SplMinHeap - Code

   <?php
   $a = array();
   for($i = 0; $i < $argv[1]; $i++) {
       $a[] = rand(1, $argv[1]);
       sort($a);
   }
   for($i = 0; $i < $argv[1]; $i++) {
       array_shift($a);
   }
SplMinHeap - Code (cont.)

    <?php
    $a = new SplMinHeap;
    for($i = 0; $i < $argv[1]; $i++) {
        $a->insert(rand(1, $argv[1]));
    }
    for($i = 0; $i < $argv[1]; $i++) {
        $a->extract();
    }
SplMinHeap - EPS
SplMinHeap - Memory
The Priority Queue
SplPriorityQueue - What

 β€’ Accepts a priority with the element value
 β€’ Element with highest priority comes out first
 β€’ Priorities may be of any comparable type
 β€’ SplPriorityQueue::compare() can be
   overridden
 β€’ Operates similarly to a heap
     – In fact, it uses a heap internally for storage
SplPriorityQueue - When

 β€’ It’s best to use this when:
   – You do not know in advance how many elements
     you want to store
   – You need to access elements in an order based on
     how priority values associated with those
     elements compare to each other
SplPriorityQueue - Code
     <?php
     $threshold = $argv[1] * 0.1;
     $a = array();
     $i = 0;
     do {
         if ($i <= $argv[1]) {
             $a[] = array($i, rand(1, 10));
             usort($a, 'priority_sort');
         }
         if ($i > $threshold) {
             array_shift($a);
         }
         $i++;
     } while (count($a));
     function priority_sort($a, $b) {
         return $a[1] - $b[1];
     }
SplPriorityQueue - Code (cont.)
   <?php
   $threshold = $argv[1] * 0.1;
   $a = new SplPriorityQueue;
   $i = 0;
   do {
        if ($i < 1) {
            $a->insert($i, rand(1,10));
        }
        if ($i > $threshold) {
            $a->extract();
        }
        $i++;
   } while (count($a));
SplPriorityQueue - EPS
SplPriorityQueue - Memory
The Set
The Composite Hash Map

    Just pretend the red pills are objects.
SplObjectStorage - What
 β€’ Combination of two data structures
   – Composite hash map: a hash map with objects for
     keys; the spl_object_hash() function must be used
     for arrays to have this capability
   – Set: focuses on a group of values rather than
     individual values with operations like union,
     intersection, difference, and element_of; no
     concept of sequential order
 β€’ Currently lacks a method for the intersection
   operation
SplObjectStorage - When

 β€’ It’s best to use this when:
   – You need to store data using composite (i.e. non-
     scalar) keys
   – You need the ability to access data using set
     operations more so than accessing it in a
     particular order
SplObjectStorage - Code
 <?php
 $a = array();
 for ($i = 0; $i < $argv[1]; $i++) {
     $object = new stdClass;
     $a[spl_object_hash($object)] = $object;
 }
 $a = array();
 $b = array();
 for ($i = 0; $i < $argv[1]; $i++) {
     $a[] = rand(1, $argv[1]);
     $b[] = rand(1, $argv[1]);
 }
 $c = array_merge($a, $b);
 $c = array_diff($a, $b);
SplObjectStorage - Code (cont.)
 <?php
 $a = new SplObjectStorage;
 for ($i = 0; $i < $argv[1]; $i++) {
     $object = new stdClass;
     $a->attach($object, $object);
 }
 $a = new SplObjectStorage;
 $b = new SplObjectStorage;
 for ($i = 0; $i < $argv[1]; $i++) {
     $a->attach((object) rand(1, $argv[1]));
     $b->attach((object) rand(1, $argv[1]));
 }
 $c = clone $a;
 $c->addAll($b);
 $c = clone $a;
 $c->removeAll($b);
SplObjectStorage - EPS
SplObjectStorage - Memory
Thank this guy

 β€’ Etienne Kneuss did a lot of the work on the
   new SPL features in PHP 5.3
Some great SPL resources

 β€’ SPL in the PHP manual
 β€’ Etienne Kneuss' blog
 β€’ "SPL to the Rescue" by Elizabeth Smith
 β€’ β€œSPL, a bridge not too far” by Michelangelo
   van Dam
 β€’ This presentation as a blog post
Possible future SPL features

 β€’ Graphs
   – Contain nodes and edges connecting them
   – Directional / non-directional
   – Cyclic / acyclic
   – Connected / unconnected
   – Edge costs
 β€’ Trees
   – Acyclic unidirectional graph
   – Hierarchical in nature
Feedback, please!

     http://joind.in/1577
That’s all, folks

 β€’   Any questions?
 β€’   http://synacor.com
 β€’   http://matthewturland.com
 β€’   me@matthewturland.com
 β€’   @elazar on Twitter
 β€’   Elazar on the Freenode IRC network

More Related Content

What's hot

Invertible-syntax ε…₯ι–€
Invertible-syntax ε…₯ι–€Invertible-syntax ε…₯ι–€
Invertible-syntax ε…₯ι–€Hiromi Ishii
Β 
Solr & Lucene @ Etsy by Gregg Donovan
Solr & Lucene @ Etsy by Gregg DonovanSolr & Lucene @ Etsy by Gregg Donovan
Solr & Lucene @ Etsy by Gregg DonovanGregg Donovan
Β 
Metaprogramming in Haskell
Metaprogramming in HaskellMetaprogramming in Haskell
Metaprogramming in HaskellHiromi Ishii
Β 
Electrify your code with PHP Generators
Electrify your code with PHP GeneratorsElectrify your code with PHP Generators
Electrify your code with PHP GeneratorsMark Baker
Β 
Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8PrinceGuru MS
Β 
DBIx::Class beginners
DBIx::Class beginnersDBIx::Class beginners
DBIx::Class beginnersleo lapworth
Β 
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
Β 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & ArraysHenry Osborne
Β 
Bioinformatics p5-bioperl v2013-wim_vancriekinge
Bioinformatics p5-bioperl v2013-wim_vancriekingeBioinformatics p5-bioperl v2013-wim_vancriekinge
Bioinformatics p5-bioperl v2013-wim_vancriekingeProf. Wim Van Criekinge
Β 
Adventures in Optimization
Adventures in OptimizationAdventures in Optimization
Adventures in OptimizationDavid Golden
Β 
Manifests of Future Past
Manifests of Future PastManifests of Future Past
Manifests of Future PastPuppet
Β 
PHP Unit 4 arrays
PHP Unit 4 arraysPHP Unit 4 arrays
PHP Unit 4 arraysKumar
Β 
Perforce Object and Record Model
Perforce Object and Record Model  Perforce Object and Record Model
Perforce Object and Record Model Perforce
Β 
Php tips-and-tricks4128
Php tips-and-tricks4128Php tips-and-tricks4128
Php tips-and-tricks4128PrinceGuru MS
Β 
Perl6 in-production
Perl6 in-productionPerl6 in-production
Perl6 in-productionAndrew Shitov
Β 
DBIx::Class introduction - 2010
DBIx::Class introduction - 2010DBIx::Class introduction - 2010
DBIx::Class introduction - 2010leo lapworth
Β 

What's hot (20)

Invertible-syntax ε…₯ι–€
Invertible-syntax ε…₯ι–€Invertible-syntax ε…₯ι–€
Invertible-syntax ε…₯ι–€
Β 
Solr & Lucene @ Etsy by Gregg Donovan
Solr & Lucene @ Etsy by Gregg DonovanSolr & Lucene @ Etsy by Gregg Donovan
Solr & Lucene @ Etsy by Gregg Donovan
Β 
Metaprogramming in Haskell
Metaprogramming in HaskellMetaprogramming in Haskell
Metaprogramming in Haskell
Β 
Electrify your code with PHP Generators
Electrify your code with PHP GeneratorsElectrify your code with PHP Generators
Electrify your code with PHP Generators
Β 
Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8
Β 
DBIx::Class beginners
DBIx::Class beginnersDBIx::Class beginners
DBIx::Class beginners
Β 
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?
Β 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
Β 
Bioinformatics p5-bioperl v2013-wim_vancriekinge
Bioinformatics p5-bioperl v2013-wim_vancriekingeBioinformatics p5-bioperl v2013-wim_vancriekinge
Bioinformatics p5-bioperl v2013-wim_vancriekinge
Β 
Adventures in Optimization
Adventures in OptimizationAdventures in Optimization
Adventures in Optimization
Β 
Manifests of Future Past
Manifests of Future PastManifests of Future Past
Manifests of Future Past
Β 
Solr @ Etsy - Apache Lucene Eurocon
Solr @ Etsy - Apache Lucene EuroconSolr @ Etsy - Apache Lucene Eurocon
Solr @ Etsy - Apache Lucene Eurocon
Β 
PHP Unit 4 arrays
PHP Unit 4 arraysPHP Unit 4 arrays
PHP Unit 4 arrays
Β 
Lithium Best
Lithium Best Lithium Best
Lithium Best
Β 
Perforce Object and Record Model
Perforce Object and Record Model  Perforce Object and Record Model
Perforce Object and Record Model
Β 
Php tips-and-tricks4128
Php tips-and-tricks4128Php tips-and-tricks4128
Php tips-and-tricks4128
Β 
Perl6 in-production
Perl6 in-productionPerl6 in-production
Perl6 in-production
Β 
Neatly folding-a-tree
Neatly folding-a-treeNeatly folding-a-tree
Neatly folding-a-tree
Β 
DBIx::Class introduction - 2010
DBIx::Class introduction - 2010DBIx::Class introduction - 2010
DBIx::Class introduction - 2010
Β 
Groovy unleashed
Groovy unleashed Groovy unleashed
Groovy unleashed
Β 

Similar to New SPL Features in PHP 5.3

Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...Dhivyaa C.R
Β 
PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007Damien Seguy
Β 
Internationalizing CakePHP Applications
Internationalizing CakePHP ApplicationsInternationalizing CakePHP Applications
Internationalizing CakePHP ApplicationsPierre MARTIN
Β 
PHP tips and tricks
PHP tips and tricks PHP tips and tricks
PHP tips and tricks Damien Seguy
Β 
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011camp_drupal_ua
Β 
Php array
Php arrayPhp array
Php arrayNikul Shah
Β 
PHP security audits
PHP security auditsPHP security audits
PHP security auditsDamien Seguy
Β 
PHP Static Code Review
PHP Static Code ReviewPHP Static Code Review
PHP Static Code ReviewDamien Seguy
Β 
PHP-04-Arrays.ppt
PHP-04-Arrays.pptPHP-04-Arrays.ppt
PHP-04-Arrays.pptLeandro660423
Β 
Chapter 2 wbp.pptx
Chapter 2 wbp.pptxChapter 2 wbp.pptx
Chapter 2 wbp.pptx40NehaPagariya
Β 
9780538745840 ppt ch06
9780538745840 ppt ch069780538745840 ppt ch06
9780538745840 ppt ch06Terry Yoast
Β 
Laravel collections an overview - Laravel SP
Laravel collections an overview - Laravel SPLaravel collections an overview - Laravel SP
Laravel collections an overview - Laravel SPMatheus Marabesi
Β 
Scaling php applications with redis
Scaling php applications with redisScaling php applications with redis
Scaling php applications with redisjimbojsb
Β 
Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)Damien Seguy
Β 

Similar to New SPL Features in PHP 5.3 (20)

Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Β 
UNIT IV (4).pptx
UNIT IV (4).pptxUNIT IV (4).pptx
UNIT IV (4).pptx
Β 
PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007
Β 
Internationalizing CakePHP Applications
Internationalizing CakePHP ApplicationsInternationalizing CakePHP Applications
Internationalizing CakePHP Applications
Β 
PHP tips and tricks
PHP tips and tricks PHP tips and tricks
PHP tips and tricks
Β 
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Β 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
Β 
Php Intermediate
Php IntermediatePhp Intermediate
Php Intermediate
Β 
Php array
Php arrayPhp array
Php array
Β 
PHP security audits
PHP security auditsPHP security audits
PHP security audits
Β 
PHP Static Code Review
PHP Static Code ReviewPHP Static Code Review
PHP Static Code Review
Β 
Smarty
SmartySmarty
Smarty
Β 
PHP-04-Arrays.ppt
PHP-04-Arrays.pptPHP-04-Arrays.ppt
PHP-04-Arrays.ppt
Β 
Chapter 2 wbp.pptx
Chapter 2 wbp.pptxChapter 2 wbp.pptx
Chapter 2 wbp.pptx
Β 
9780538745840 ppt ch06
9780538745840 ppt ch069780538745840 ppt ch06
9780538745840 ppt ch06
Β 
SPL, not a bridge too far
SPL, not a bridge too farSPL, not a bridge too far
SPL, not a bridge too far
Β 
Laravel collections an overview - Laravel SP
Laravel collections an overview - Laravel SPLaravel collections an overview - Laravel SP
Laravel collections an overview - Laravel SP
Β 
Scaling php applications with redis
Scaling php applications with redisScaling php applications with redis
Scaling php applications with redis
Β 
Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)
Β 
[Start] Scala
[Start] Scala[Start] Scala
[Start] Scala
Β 

More from Matthew Turland

New SPL Features in PHP 5.3 (TEK-X)
New SPL Features in PHP 5.3 (TEK-X)New SPL Features in PHP 5.3 (TEK-X)
New SPL Features in PHP 5.3 (TEK-X)Matthew Turland
Β 
Web Scraping with PHP
Web Scraping with PHPWeb Scraping with PHP
Web Scraping with PHPMatthew Turland
Β 
Web Scraping with PHP
Web Scraping with PHPWeb Scraping with PHP
Web Scraping with PHPMatthew Turland
Β 
Open Source Networking with Vyatta
Open Source Networking with VyattaOpen Source Networking with Vyatta
Open Source Networking with VyattaMatthew Turland
Β 
When RSS Fails: Web Scraping with HTTP
When RSS Fails: Web Scraping with HTTPWhen RSS Fails: Web Scraping with HTTP
When RSS Fails: Web Scraping with HTTPMatthew Turland
Β 
Open Source Content Management Systems
Open Source Content Management SystemsOpen Source Content Management Systems
Open Source Content Management SystemsMatthew Turland
Β 
PHP Basics for Designers
PHP Basics for DesignersPHP Basics for Designers
PHP Basics for DesignersMatthew Turland
Β 
Web Scraping with PHP
Web Scraping with PHPWeb Scraping with PHP
Web Scraping with PHPMatthew Turland
Β 
Creating Web Services with Zend Framework - Matthew Turland
Creating Web Services with Zend Framework - Matthew TurlandCreating Web Services with Zend Framework - Matthew Turland
Creating Web Services with Zend Framework - Matthew TurlandMatthew Turland
Β 
The OpenSolaris Operating System and Sun xVM VirtualBox - Blake Deville
The OpenSolaris Operating System and Sun xVM VirtualBox - Blake DevilleThe OpenSolaris Operating System and Sun xVM VirtualBox - Blake Deville
The OpenSolaris Operating System and Sun xVM VirtualBox - Blake DevilleMatthew Turland
Β 
Utilizing the Xen Hypervisor in business practice - Bryan Fusilier
Utilizing the Xen Hypervisor in business practice - Bryan FusilierUtilizing the Xen Hypervisor in business practice - Bryan Fusilier
Utilizing the Xen Hypervisor in business practice - Bryan FusilierMatthew Turland
Β 
The Ruby Programming Language - Ryan Farnell
The Ruby Programming Language - Ryan FarnellThe Ruby Programming Language - Ryan Farnell
The Ruby Programming Language - Ryan FarnellMatthew Turland
Β 
PDQ Programming Languages plus an overview of Alice - Frank Ducrest
PDQ Programming Languages plus an overview of Alice - Frank DucrestPDQ Programming Languages plus an overview of Alice - Frank Ducrest
PDQ Programming Languages plus an overview of Alice - Frank DucrestMatthew Turland
Β 
Getting Involved in Open Source - Matthew Turland
Getting Involved in Open Source - Matthew TurlandGetting Involved in Open Source - Matthew Turland
Getting Involved in Open Source - Matthew TurlandMatthew Turland
Β 

More from Matthew Turland (15)

New SPL Features in PHP 5.3 (TEK-X)
New SPL Features in PHP 5.3 (TEK-X)New SPL Features in PHP 5.3 (TEK-X)
New SPL Features in PHP 5.3 (TEK-X)
Β 
Sinatra
SinatraSinatra
Sinatra
Β 
Web Scraping with PHP
Web Scraping with PHPWeb Scraping with PHP
Web Scraping with PHP
Β 
Web Scraping with PHP
Web Scraping with PHPWeb Scraping with PHP
Web Scraping with PHP
Β 
Open Source Networking with Vyatta
Open Source Networking with VyattaOpen Source Networking with Vyatta
Open Source Networking with Vyatta
Β 
When RSS Fails: Web Scraping with HTTP
When RSS Fails: Web Scraping with HTTPWhen RSS Fails: Web Scraping with HTTP
When RSS Fails: Web Scraping with HTTP
Β 
Open Source Content Management Systems
Open Source Content Management SystemsOpen Source Content Management Systems
Open Source Content Management Systems
Β 
PHP Basics for Designers
PHP Basics for DesignersPHP Basics for Designers
PHP Basics for Designers
Β 
Web Scraping with PHP
Web Scraping with PHPWeb Scraping with PHP
Web Scraping with PHP
Β 
Creating Web Services with Zend Framework - Matthew Turland
Creating Web Services with Zend Framework - Matthew TurlandCreating Web Services with Zend Framework - Matthew Turland
Creating Web Services with Zend Framework - Matthew Turland
Β 
The OpenSolaris Operating System and Sun xVM VirtualBox - Blake Deville
The OpenSolaris Operating System and Sun xVM VirtualBox - Blake DevilleThe OpenSolaris Operating System and Sun xVM VirtualBox - Blake Deville
The OpenSolaris Operating System and Sun xVM VirtualBox - Blake Deville
Β 
Utilizing the Xen Hypervisor in business practice - Bryan Fusilier
Utilizing the Xen Hypervisor in business practice - Bryan FusilierUtilizing the Xen Hypervisor in business practice - Bryan Fusilier
Utilizing the Xen Hypervisor in business practice - Bryan Fusilier
Β 
The Ruby Programming Language - Ryan Farnell
The Ruby Programming Language - Ryan FarnellThe Ruby Programming Language - Ryan Farnell
The Ruby Programming Language - Ryan Farnell
Β 
PDQ Programming Languages plus an overview of Alice - Frank Ducrest
PDQ Programming Languages plus an overview of Alice - Frank DucrestPDQ Programming Languages plus an overview of Alice - Frank Ducrest
PDQ Programming Languages plus an overview of Alice - Frank Ducrest
Β 
Getting Involved in Open Source - Matthew Turland
Getting Involved in Open Source - Matthew TurlandGetting Involved in Open Source - Matthew Turland
Getting Involved in Open Source - Matthew Turland
Β 

Recently uploaded

Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
Β 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
Β 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
Β 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
Β 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
Β 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
Β 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
Β 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
Β 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
Β 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
Β 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
Β 
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
Β 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
Β 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
Β 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
Β 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
Β 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
Β 

Recently uploaded (20)

Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
Β 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
Β 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Β 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Β 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
Β 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
Β 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Β 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
Β 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
Β 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
Β 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Β 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
Β 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
Β 
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
Β 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
Β 
Hot Sexy call girls in Panjabi Bagh πŸ” 9953056974 πŸ” Delhi escort Service
Hot Sexy call girls in Panjabi Bagh πŸ” 9953056974 πŸ” Delhi escort ServiceHot Sexy call girls in Panjabi Bagh πŸ” 9953056974 πŸ” Delhi escort Service
Hot Sexy call girls in Panjabi Bagh πŸ” 9953056974 πŸ” Delhi escort Service
Β 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
Β 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
Β 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
Β 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Β 

New SPL Features in PHP 5.3

  • 1. New SPL Features in PHP 5.3 Matthew Turland TEK-X May 20, 2010
  • 2. Hi! My name is… β€’ Senior Platform Engineer for Synacor, Inc. β€’ Former author and TE for php|architect β€’ Author of Web Scraping with PHP β€’ Past contributor to Zend Framework β€’ Lead developer of Phergie β€’ ULL alumni with a BS in computer science
  • 3. And I work for… β€’ Provides internet solutions to ISPs, media companies, and advertisers β€’ International company with offices in Buffalo, New York City, Los Angeles, and Amsterdam β€’ Clientele includes most of the top 20 cable providers in the United States β€’ Great company – join us!
  • 4. What about you? β€’ Used the SPL before? β€’ Using PHP 5.3? β€’ Computer science background? β€’ Knowledge of data structures?
  • 5. Pre-5.3 SPL Features β€’ Classes: ArrayObject, SplFileInfo, SplSubject, SplObserver, etc. β€’ Iterators: RecursiveIteratorIterator, FilterIterator, LimitIterator, etc. β€’ Interfaces: ArrayAccess, Countable, Iterator, IteratorAggregate, etc. β€’ Functions: spl_autoload_register, iterator_to_array, spl_object_hash, etc.
  • 6. Containers β€œA container is a class, a data structure, or an abstract data type whose instances are collections of other objects. They are used to store objects in an organized way following specific access rules.” Container (data structure) - Wikipedia
  • 7. Why containers? β€’ We already have arrays and strings! array() 'string'
  • 8. Two excellent reasons β€’ Versus traditional arrays, there is potential for: – Less CPU usage – Less memory usage
  • 9. Arrays are (not always) great β€’ Flexible general purpose container β€’ Underlying hash table algorithm is not always ideal for the task at hand
  • 10. Warning: Benchmarks Ahead β€’ Lies, Outrageous Lies, and Benchmarks β€’ PHP 5.3.2 compiled on Ubuntu 9.10 β€’ Intel Core2Duo 1.83 GHz, 4 GB DDR2 RAM β€’ Performance results are shown in executions per second rather than time per execution to avoid really small numbers β€’ Code and results
  • 12. SplFixedArray - What β€’ Like an array, but with a fixed length β€’ Only allows integers >= 0 for keys β€’ Can be resized, but at a cost β€’ Not compatible with array functions
  • 13. SplFixedArray - When β€’ It’s best to use this when: – You know in advance how many elements you want to store (e.g. mysql_num_rows) – You only need to access elements in sequential order
  • 14. SplFixedArray - Code <?php $a = array(); for ($i = 0; $i < $argv[1]; $i++) { $a[$i] = $i; $i = $a[$i]; } <?php $a = new SplFixedArray($argv[1]); for ($i = 0; $i < $argv[1]; $i++) { $a[$i] = $i; $i = $a[$i]; }
  • 17. SplDoublyLinkedList - What β€’ Mainly intended as a parent class β€’ Same unlimited size as arrays without the associated hash map algorithm β€’ Less performance, but more memory efficiency
  • 18. SplDoublyLinkedList - When β€’ It’s best to use this when: – You do not know in advance how many elements you want to store – You only need to access elements in sequential order
  • 19. SplDoublyLinkedList - Code <?php $a = array(); for ($i = 0; $i < $argv[1]; $i++) { $a[] = $i; $i = $a[$i]; } <?php $a = new SplDoublyLinkedList($argv[1]); for ($i = 0; $i < $argv[1]; $i++) { $a[] = $i; $i = $a[$i]; }
  • 23. SplStack - What β€’ 2 operations – Push: [] for both array and SplStack – Pop: array_pop() vs SplStack::pop() β€’ Last In, First Out (LIFO) – The last item pushed onto the top of the stack is the first item that will be popped off of the top of the stack
  • 24. SplStack - When β€’ It’s best to use this when: – You do not know in advance how many elements you want to store – You only ever need to access the last element you stored
  • 25. SplStack - Code <?php $a = array(); for($i = 0; $i < $argv[1]; $i++) { $a[] = $i; } for($i = 0; $i < $argv[1]; $i++) { array_pop($a); }
  • 26. SplStack - Code (cont.) <?php $a = new SplStack; for($i = 0; $i < $argv[1]; $i++) { $a[] = $i; } for($i = 0; $i < $argv[1]; $i++) { $a->pop(); }
  • 30. SplQueue - What β€’ 2 operations – Enqueue: [] for both array and SplQueue – Dequeue: array_shift() vs SplQueue::dequeue() β€’ First In, First Out (FIFO) – The first item added to the end of the queue will be the first item removed from the front of the queue
  • 31. SplQueue - When β€’ It’s best to use this when: – You do not know in advance how many elements you want to store – You only ever need to access the remaining element that was stored earliest
  • 32. SplQueue - Code <?php $a = array(); for($i = 0; $i < $argv[1]; $i++) { $a[] = $i; } for($i = 0; $i < $argv[1]; $i++) { array_shift($a); }
  • 33. SplQueue - Code (cont.) <?php $a = new SplQueue; for($i = 0; $i < $argv[1]; $i++) { $a[] = $i; } for($i = 0; $i < $argv[1]; $i++) { $a->dequeue(); }
  • 37. SplHeap - What β€’ 2 operations – Insert: [] + sort vs SplHeap::insert() – Remove: array_shift() vs SplHeap::extract() β€’ Internally reorders items based on comparison – SplHeap::compare() can be overridden β€’ Subclasses – SplMinHeap – SplMaxHeap β€’ Better worst-case scenario performance versus arrays (heap sort versus quick sort)
  • 38. SplHeap - When β€’ It’s best to use this when: – You do not know in advance how many elements you want to store – You need to access elements in an order based on how they compare to each other
  • 39. SplMinHeap - Code <?php $a = array(); for($i = 0; $i < $argv[1]; $i++) { $a[] = rand(1, $argv[1]); sort($a); } for($i = 0; $i < $argv[1]; $i++) { array_shift($a); }
  • 40. SplMinHeap - Code (cont.) <?php $a = new SplMinHeap; for($i = 0; $i < $argv[1]; $i++) { $a->insert(rand(1, $argv[1])); } for($i = 0; $i < $argv[1]; $i++) { $a->extract(); }
  • 44. SplPriorityQueue - What β€’ Accepts a priority with the element value β€’ Element with highest priority comes out first β€’ Priorities may be of any comparable type β€’ SplPriorityQueue::compare() can be overridden β€’ Operates similarly to a heap – In fact, it uses a heap internally for storage
  • 45. SplPriorityQueue - When β€’ It’s best to use this when: – You do not know in advance how many elements you want to store – You need to access elements in an order based on how priority values associated with those elements compare to each other
  • 46. SplPriorityQueue - Code <?php $threshold = $argv[1] * 0.1; $a = array(); $i = 0; do { if ($i <= $argv[1]) { $a[] = array($i, rand(1, 10)); usort($a, 'priority_sort'); } if ($i > $threshold) { array_shift($a); } $i++; } while (count($a)); function priority_sort($a, $b) { return $a[1] - $b[1]; }
  • 47. SplPriorityQueue - Code (cont.) <?php $threshold = $argv[1] * 0.1; $a = new SplPriorityQueue; $i = 0; do { if ($i < 1) { $a->insert($i, rand(1,10)); } if ($i > $threshold) { $a->extract(); } $i++; } while (count($a));
  • 51. The Composite Hash Map Just pretend the red pills are objects.
  • 52. SplObjectStorage - What β€’ Combination of two data structures – Composite hash map: a hash map with objects for keys; the spl_object_hash() function must be used for arrays to have this capability – Set: focuses on a group of values rather than individual values with operations like union, intersection, difference, and element_of; no concept of sequential order β€’ Currently lacks a method for the intersection operation
  • 53. SplObjectStorage - When β€’ It’s best to use this when: – You need to store data using composite (i.e. non- scalar) keys – You need the ability to access data using set operations more so than accessing it in a particular order
  • 54. SplObjectStorage - Code <?php $a = array(); for ($i = 0; $i < $argv[1]; $i++) { $object = new stdClass; $a[spl_object_hash($object)] = $object; } $a = array(); $b = array(); for ($i = 0; $i < $argv[1]; $i++) { $a[] = rand(1, $argv[1]); $b[] = rand(1, $argv[1]); } $c = array_merge($a, $b); $c = array_diff($a, $b);
  • 55. SplObjectStorage - Code (cont.) <?php $a = new SplObjectStorage; for ($i = 0; $i < $argv[1]; $i++) { $object = new stdClass; $a->attach($object, $object); } $a = new SplObjectStorage; $b = new SplObjectStorage; for ($i = 0; $i < $argv[1]; $i++) { $a->attach((object) rand(1, $argv[1])); $b->attach((object) rand(1, $argv[1])); } $c = clone $a; $c->addAll($b); $c = clone $a; $c->removeAll($b);
  • 58. Thank this guy β€’ Etienne Kneuss did a lot of the work on the new SPL features in PHP 5.3
  • 59. Some great SPL resources β€’ SPL in the PHP manual β€’ Etienne Kneuss' blog β€’ "SPL to the Rescue" by Elizabeth Smith β€’ β€œSPL, a bridge not too far” by Michelangelo van Dam β€’ This presentation as a blog post
  • 60. Possible future SPL features β€’ Graphs – Contain nodes and edges connecting them – Directional / non-directional – Cyclic / acyclic – Connected / unconnected – Edge costs β€’ Trees – Acyclic unidirectional graph – Hierarchical in nature
  • 61. Feedback, please! http://joind.in/1577
  • 62. That’s all, folks β€’ Any questions? β€’ http://synacor.com β€’ http://matthewturland.com β€’ me@matthewturland.com β€’ @elazar on Twitter β€’ Elazar on the Freenode IRC network