SlideShare a Scribd company logo
SPL: The Missing Link in Development
Jake Smith
Dallas PHP - 7/13/2010
What is SPL?

•   A	
  library	
  of	
  standard	
  interfaces,	
  classes,	
  
    and	
  functions	
  designed	
  to	
  solve	
  common	
  
    programming	
  problems	
  and	
  allow	
  engine	
  
    overloading.




        Definition Source: http://elizabethmariesmith.com/
SPL Background

• Provides Interfaces, Classes and Functions
• As of PHP 5.3 you can not turn off SPL
• Poor documentation root of poor
  adoption.
SPL Autoloading
Before SPL Autoload
set_include_path(dirname(__FILE__) . '/lib' . PATH_SEPARATOR . get_include_path());
function __autoload($class_name) {
    $path = dirname(__FILE__) . '/lib/' . str_replace('_', '/', strtolower
($class_name)) . '.php';
    if (file_exists($path)) {
        require $path;
    } else {
        die('Class ' . $path . ' Not Found');
    }
}




                                 Class Name
              <?php
              class Form_Element_Text extends Form_Element
              {

                  public function __construct($name = '', $attrs = array())
                  {
                      $this->_name = $name;
                      $this->_attrs = $attrs;
                  }
Autoloading w/SPL
 <?php
     /*** nullify any existing autoloads ***/
     spl_autoload_register(null, false);

     /*** specify extensions that may be loaded ***/
     spl_autoload_extensions('.php, .class.php');

     /*** class Loader ***/
     function classLoader($class)
     {
         $filename = strtolower($class) . '.class.php';
         $file ='classes/' . $filename;
         if (!file_exists($file))
         {
             return false;
         }
         include $file;
     }

     /*** register the loader functions ***/
     spl_autoload_register('classLoader');




Example Source: http://www.phpro.org/tutorials/SPL-Autoload.html
Multiple Autoloaders

 <?php
     /*** nullify any existing autoloads ***/
     spl_autoload_register(null, false);

     spl_autoload_register(array('Doctrine_Core', 'autoload'));
     spl_autoload_register(array('Doctrine_Core', 'modelsAutoload'));
Multiple Autoloaders
<?php
class Doctrine_Core
{
    public static function autoload($className)
    {
        if (strpos($className, 'sfYaml') === 0) {
            require dirname(__FILE__) . '/Parser/sfYaml/' . $className . '.php';

            return true;
        }

        if (0 !== stripos($className, 'Doctrine_') || class_exists($className, false) || interface_exists($className, false)) {
            return false;
        }

        $class = self::getPath() . DIRECTORY_SEPARATOR . str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';

        if (file_exists($class)) {
            require $class;

            return true;
        }

        return false;
    }
SPL Functions
iterator_to_array


• Takes an iterator object, an object that
  implements Traversable
  • All iterators implement Traversable
spl_object_hash

• MD5 hash of internal pointer
• When objects are destroyed their object
  hash is released
 • Object Hash ID can/will be reused after
    destruction.
SPL Classes


• ArrayObject
• SplFileInfo
ArrayObject

• Allows objects to act like arrays
• Does not allow usage of array functions on
  object
 • Built in methods: ksort, usort, asort,
    getArrayCopy
SplFileInfo

• Object that returns information on Files/
  Folders
• isDir, isFile, isReadable, isWritable, getPerms
  (returns int), etc.



      Example Source: http://us3.php.net/manual/en/class.splfileinfo.php
SPL Interfaces
• ArrayAccess
• Iterator
• RecursiveIterator
• Countable
• SeekableIterator
• SplSubject/SplObserver
Observer Pattern (SPL)

• Great for applying hooks
 • Exception Handling
 • User Authentication
SplSubject
           <?php
           class ExceptionHandler implements SplSubject
           {
               private $_observers = array();

               public function attach(SplObserver $observer)
               {
                   $id = spl_object_hash($observer);
                   $this->_observers[$id] = $observer;
               }

               public function detach(SplObserver $observer)
               {
                   $id = spl_object_hash($observer);
                   unset($this->_observers[$id]);
               }

               public function notify()
               {
                   foreach($this->_observers as $obs) {
                       $obs->update($this);
                   }
               }

               public function handle(Exception $e)
               {
                   $this->exception = $e;
                   $this->notify();
               }
           }


Example Source: http://devzone.zend.com/article/12229
SplObserver
        Class Mailer implements SplObserver {
            public function update(SplSubject $subject)
            {
                // Do something with subject object
            }
        }

        // Create the ExceptionHandler
        $handler = new ExceptionHandler();

        // Attach an Exception Logger and Mailer
        $handler->attach(new Mailer());

        // Set ExceptionHandler::handle() as the default
        set_exception_handler(array($handler, 'handle'));




Example Source: http://devzone.zend.com/article/12229
ArrayAccess
• OffsetExists - Values exists for key, returns
  boolean
• OffsetSet - Set value for key
• OffsetGet - Return value for key
• OffsetUnset - Remove value from array
  •    Note that if the array is numerically indexed, a call to array_values() will be required to re-index
       the array if that is the behaviour required.




      Example Source: http://www.phpro.org/tutorials/Introduction-to-SPL-ArrayAccess.html
ArrayAccess Example
             <?php
             class book implements ArrayAccess
             {
                 public $title;

                 public $author;

                 public $isbn;

                 public function offsetExists( $offset )
                 {
                     return isset( $this->$offset );
                 }

                 public function offsetSet( $offset, $value)
                 {
                     $this->$offset = $value;
                 }

                 public function offsetGet( $offset )
                 {
                     return $this->$offset;
                 }

                 public function offsetUnset( $offset )
                 {
                     unset( $this->$offset );
                 }
             }



 Example Source: http://www.phpro.org/tutorials/Introduction-to-SPL-ArrayAccess.html
Iterator

• Provides basic iterator functionality
  (foreach)
• Interface requires the following methods
 • current(), key(), next(), rewind(), valid()
Recursive Iterator

• A foreach only goes top level, but many
  times you need to dig deeper
• Recursive Iterator extends Iterator and
  requires hasChildren() and getChildren()
Countable
• Internal Counter
             <?php
             class loopy
             {
                 public function count()
                 {
                     static $count = 0;
                     return $count++;
                 }

                 public function access()
                 {
                     $this->count();
                     // Method logic
                 }
             }
SeekableIterator
• Other iterators must start at beginning of
  an array, but seekable allows you to change
  iteration start point.
     <?php

     class PartyMemberIterator implements SeekableIterator
     {
         public function seek($index)
         {
             $this->rewind();
             $position = 0;

              while ($position < $index && $this->valid()) {
                  $this->next();
                  $position++;
              }

              if (!$this->valid()) {
                  throw new OutOfBoundsException('Invalid position');
              }
         }


     Example Source: http://devzone.zend.com/article/2565
SPL Iterators

• ArrayIterator
• LimitIterator
• DirectoryIterator
• RecursiveDirectoryIterator
• GlobIterator
ArrayIterator

• Implements: Iterator, Traversable,
  ArrayAccess, SeekableIterator, Countable
• Used to Iterate over ArrayObject or PHP
  array
ArrayIterator
<?php
// Using While
/*** create a new object ***/
$object = new ArrayIterator($array);

/*** rewind to the beginning of the array ***/
$object->rewind();

/*** check for valid member ***/
while($object->valid())
{
    /*** echo the key and current value ***/
    echo $object->key().' -&gt; '.$object->current().'<br />';

     /*** hop to the next array member ***/
     $object->next();
}

// Using Foreach
$object = new ArrayIterator($array);
foreach($object as $key=>$value)
{
echo $key.' => '.$value.'<br />';
}



Example Source: http://www.phpro.org/tutorials/Introduction-to-SPL.html#6
LimitIterator
• Used similar to Limit in SQL
  <?php
  // Show 10 files/folders starting from the 3rd.
  $offset = 3;

  $limit = 10;

  $filepath = '/var/www/vhosts/mysite/images'

  $it = new LimitIterator(new DirectoryIterator($filepath), $offset, $limit);

  foreach($it as $r)
  {
      // output the key and current array value
      echo $it->key().' -- '.$it->current().'<br />';
  }
DirectoryIterator

• If you’re accessing the filesystem this is the
  iterator for you!
• Returns SplFileInfo object
DirectoryIterator
<?php                                     <?php
$hdl = opendir('./');                     try
while ($dirEntry = readdir($hdl))         {
{                                             /*** class create new DirectoryIterator Object ***/
    if (substr($dirEntry, 0, 1) != '.')       foreach ( new DirectoryIterator('./') as $Item )
    {                                         {
        if(!is_file($dirEntry))                   echo $Item.'<br />';
        {                                     }
            continue;                     }
        }                                 /*** if an exception is thrown, catch it here ***/
        $listing[] = $dirEntry;           catch(Exception $e)
    }                                     {
}                                             echo 'No files Found!<br />';
closedir($hdl);                           }
foreach($listing as $my_file)
{
    echo $my_file.'<br />';
}
RecursiveDirectory
          Iterator
• Move out of the top level and get all
    children files/folders
<?php
    $dir = '/Users/jsmith/Sites/vhosts/test.local/wwwroot';
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
    // could use CHILD_FIRST if you so wish
    foreach ($iterator as $file) {
        echo $file . "<br />";
    }
GlobIterator (5.3)

• Very Similar to DirectoryIterator
• Only use if you want to convert old glob
  code into an iterator object
• returns SplFileInfo Objects
SPL Exceptions
• Logic Exception
                                                 • RuntimeException
 • BadFunction
                                                  • OutOfBounds
 • BadMethodCall
                                                  • Range
 • InvalidArgument
                                                  • UnexpectedValue
 • OutOfRange
                                                  • Underflow
      Example Source: http://www.php.net/manual/en/spl.exceptions.php
New SPL in PHP 5.3
SplFixedArray

• Array with pre-defined dimensions
• Shows great speed for setting and
  retrieving
• If you change Array dimensions, it will
  crawl.
SplHeap

• Automatically reorder after insert, based
  off of compare() method
• Extract is similar to array_shift()
• Great memory usage!

      Example Source: http://www.slideshare.net/tobias382/new-spl-features-in-php-53
SplMaxHeap
• Subclass of SplHeap
• When you extract() a value it will return in
  order from greatest to least
                          <?php
                          $heap = new SplMaxHeap();
                          $heap->insert('b');
                          $heap->insert('a');
                          $heap->insert('c');

                          echo $heap->extract()."n";
                          echo $heap->extract()."n";
                          echo $heap->extract()."n";
                          // OUTPUT:
                          // c
                          // b
                          // a



     Example Source: http://www.alberton.info/php_5.3_spl_data_structures.html
SplMinHeap
• Subclass of SplHeap
• When you extract() a value it will return in
  order from least to greatest
                          <?php
                          $heap = new SplMinHeap();
                          $heap->insert('b');
                          $heap->insert('a');
                          $heap->insert('c');

                          echo $heap->extract()."n";
                          echo $heap->extract()."n";
                          echo $heap->extract()."n";

                          //   OUTPUT:
                          //   a
                          //   b
                          //   c

     Example Source: http://www.alberton.info/php_5.3_spl_data_structures.html
SplDoublyLinkedList

• Do not know size of list/array
• Can only be read sequentially
• Less processing power required, on large
  data sets provides better memory usage
SplStack


• Method: push and pop
• LIFO
SplQueue


• Methods: enqueue and dequeue
• FIFO
Questions?
Useful Links
•   SPL in 5.3

    •   http://www.alberton.info/
        php_5.3_spl_data_structures.html

    •   http://www.slideshare.net/tobias382/new-spl-features-in-
        php-53

•   Intro to SPL

    •   http://www.phpro.org/tutorials/Introduction-to-SPL.html

    •   http://www.slideshare.net/DragonBe/spl-not-a-bridge-too-
        far
Thanks for listening!
Contact Information
[t]: @jakefolio
[e]: jake@dallasphp.org
[w]: http://www.jakefolio.com
[irc]: #dallasphp

More Related Content

What's hot

Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate Frameworks
Nate Abele
 
Introducing Assetic (NYPHP)
Introducing Assetic (NYPHP)Introducing Assetic (NYPHP)
Introducing Assetic (NYPHP)Kris Wallsmith
 
A Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP GeneratorsA Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP Generators
Mark Baker
 
New in php 7
New in php 7New in php 7
New in php 7
Vic Metcalfe
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
Nate Abele
 
Dependency Injection with PHP 5.3
Dependency Injection with PHP 5.3Dependency Injection with PHP 5.3
Dependency Injection with PHP 5.3
Fabien Potencier
 
Php tips-and-tricks4128
Php tips-and-tricks4128Php tips-and-tricks4128
Php tips-and-tricks4128PrinceGuru MS
 
Speed up your developments with Symfony2
Speed up your developments with Symfony2Speed up your developments with Symfony2
Speed up your developments with Symfony2Hugo Hamon
 
PHP Conference Asia 2016
PHP Conference Asia 2016PHP Conference Asia 2016
PHP Conference Asia 2016
Britta Alex
 
Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8PrinceGuru MS
 
Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL Iterators
Mark Baker
 
Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
Vineet Kumar Saini
 
PHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolvePHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolve
XSolve
 
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
James Titcumb
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
Henry Osborne
 
A Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP GeneratorsA Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP Generators
Mark Baker
 
News of the Symfony2 World
News of the Symfony2 WorldNews of the Symfony2 World
News of the Symfony2 WorldFabien Potencier
 

What's hot (20)

Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate Frameworks
 
Introducing Assetic (NYPHP)
Introducing Assetic (NYPHP)Introducing Assetic (NYPHP)
Introducing Assetic (NYPHP)
 
Sorting arrays in PHP
Sorting arrays in PHPSorting arrays in PHP
Sorting arrays in PHP
 
A Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP GeneratorsA Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP Generators
 
New in php 7
New in php 7New in php 7
New in php 7
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
 
Dependency Injection with PHP 5.3
Dependency Injection with PHP 5.3Dependency Injection with PHP 5.3
Dependency Injection with PHP 5.3
 
Lithium Best
Lithium Best Lithium Best
Lithium Best
 
Php tips-and-tricks4128
Php tips-and-tricks4128Php tips-and-tricks4128
Php tips-and-tricks4128
 
Speed up your developments with Symfony2
Speed up your developments with Symfony2Speed up your developments with Symfony2
Speed up your developments with Symfony2
 
PHP Conference Asia 2016
PHP Conference Asia 2016PHP Conference Asia 2016
PHP Conference Asia 2016
 
Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8
 
Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL Iterators
 
Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
 
PHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolvePHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolve
 
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
 
Symfony2 - WebExpo 2010
Symfony2 - WebExpo 2010Symfony2 - WebExpo 2010
Symfony2 - WebExpo 2010
 
A Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP GeneratorsA Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP Generators
 
News of the Symfony2 World
News of the Symfony2 WorldNews of the Symfony2 World
News of the Symfony2 World
 

Viewers also liked

Unsung Heroes of PHP
Unsung Heroes of PHPUnsung Heroes of PHP
Unsung Heroes of PHP
jsmith92
 
LESS is More
LESS is MoreLESS is More
LESS is Morejsmith92
 
Parsimonious Relevance and Concept Models - CLEF 2008 Domain Specific Talk - ...
Parsimonious Relevance and Concept Models - CLEF 2008 Domain Specific Talk - ...Parsimonious Relevance and Concept Models - CLEF 2008 Domain Specific Talk - ...
Parsimonious Relevance and Concept Models - CLEF 2008 Domain Specific Talk - ...Edgar Meij
 
Doing more with LESS
Doing more with LESSDoing more with LESS
Doing more with LESS
jsmith92
 
Drawing the Line with Browser Compatibility
Drawing the Line with Browser CompatibilityDrawing the Line with Browser Compatibility
Drawing the Line with Browser Compatibilityjsmith92
 
Intro to Micro-frameworks
Intro to Micro-frameworksIntro to Micro-frameworks
Intro to Micro-frameworks
jsmith92
 

Viewers also liked (6)

Unsung Heroes of PHP
Unsung Heroes of PHPUnsung Heroes of PHP
Unsung Heroes of PHP
 
LESS is More
LESS is MoreLESS is More
LESS is More
 
Parsimonious Relevance and Concept Models - CLEF 2008 Domain Specific Talk - ...
Parsimonious Relevance and Concept Models - CLEF 2008 Domain Specific Talk - ...Parsimonious Relevance and Concept Models - CLEF 2008 Domain Specific Talk - ...
Parsimonious Relevance and Concept Models - CLEF 2008 Domain Specific Talk - ...
 
Doing more with LESS
Doing more with LESSDoing more with LESS
Doing more with LESS
 
Drawing the Line with Browser Compatibility
Drawing the Line with Browser CompatibilityDrawing the Line with Browser Compatibility
Drawing the Line with Browser Compatibility
 
Intro to Micro-frameworks
Intro to Micro-frameworksIntro to Micro-frameworks
Intro to Micro-frameworks
 

Similar to SPL: The Missing Link in Development

Oops in php
Oops in phpOops in php
Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4
Jeff Carouth
 
Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL Iterators
Mark Baker
 
Aura Project for PHP
Aura Project for PHPAura Project for PHP
Aura Project for PHPHari K T
 
Practical PHP 5.3
Practical PHP 5.3Practical PHP 5.3
Practical PHP 5.3
Nate Abele
 
Solid principles
Solid principlesSolid principles
Solid principles
Bastian Feder
 
Spl Not A Bridge Too Far phpNW09
Spl Not A Bridge Too Far phpNW09Spl Not A Bridge Too Far phpNW09
Spl Not A Bridge Too Far phpNW09
Michelangelo van Dam
 
php AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdfphp AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdf
SVN Polytechnic Kalan Sultanpur UP
 
ekb.py - Python VS ...
ekb.py - Python VS ...ekb.py - Python VS ...
ekb.py - Python VS ...
it-people
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest UpdatesIftekhar Eather
 
Intermediate PHP
Intermediate PHPIntermediate PHP
Intermediate PHP
Bradley Holt
 
08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboards08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboards
Denis Ristic
 
Ch8(oop)
Ch8(oop)Ch8(oop)
Ch8(oop)
Chhom Karath
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
Lars Jankowfsky
 
Intro to The PHP SPL
Intro to The PHP SPLIntro to The PHP SPL
Intro to The PHP SPL
Chris Tankersley
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et Pimple
Hugo Hamon
 
FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3
Toni Kolev
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5
Leonardo Proietti
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
Stoyan Stefanov
 

Similar to SPL: The Missing Link in Development (20)

Oops in php
Oops in phpOops in php
Oops in php
 
Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4
 
Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL Iterators
 
Aura Project for PHP
Aura Project for PHPAura Project for PHP
Aura Project for PHP
 
Practical PHP 5.3
Practical PHP 5.3Practical PHP 5.3
Practical PHP 5.3
 
Solid principles
Solid principlesSolid principles
Solid principles
 
Spl Not A Bridge Too Far phpNW09
Spl Not A Bridge Too Far phpNW09Spl Not A Bridge Too Far phpNW09
Spl Not A Bridge Too Far phpNW09
 
php AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdfphp AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdf
 
ekb.py - Python VS ...
ekb.py - Python VS ...ekb.py - Python VS ...
ekb.py - Python VS ...
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
 
Intermediate PHP
Intermediate PHPIntermediate PHP
Intermediate PHP
 
08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboards08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboards
 
Ch8(oop)
Ch8(oop)Ch8(oop)
Ch8(oop)
 
PHP pod mikroskopom
PHP pod mikroskopomPHP pod mikroskopom
PHP pod mikroskopom
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
Intro to The PHP SPL
Intro to The PHP SPLIntro to The PHP SPL
Intro to The PHP SPL
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et Pimple
 
FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
 

Recently uploaded

FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
Abida Shariff
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 

Recently uploaded (20)

FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 

SPL: The Missing Link in Development

  • 1. SPL: The Missing Link in Development Jake Smith Dallas PHP - 7/13/2010
  • 2. What is SPL? • A  library  of  standard  interfaces,  classes,   and  functions  designed  to  solve  common   programming  problems  and  allow  engine   overloading. Definition Source: http://elizabethmariesmith.com/
  • 3. SPL Background • Provides Interfaces, Classes and Functions • As of PHP 5.3 you can not turn off SPL • Poor documentation root of poor adoption.
  • 5. Before SPL Autoload set_include_path(dirname(__FILE__) . '/lib' . PATH_SEPARATOR . get_include_path()); function __autoload($class_name) { $path = dirname(__FILE__) . '/lib/' . str_replace('_', '/', strtolower ($class_name)) . '.php'; if (file_exists($path)) { require $path; } else { die('Class ' . $path . ' Not Found'); } } Class Name <?php class Form_Element_Text extends Form_Element { public function __construct($name = '', $attrs = array()) { $this->_name = $name; $this->_attrs = $attrs; }
  • 6. Autoloading w/SPL <?php /*** nullify any existing autoloads ***/ spl_autoload_register(null, false); /*** specify extensions that may be loaded ***/ spl_autoload_extensions('.php, .class.php'); /*** class Loader ***/ function classLoader($class) { $filename = strtolower($class) . '.class.php'; $file ='classes/' . $filename; if (!file_exists($file)) { return false; } include $file; } /*** register the loader functions ***/ spl_autoload_register('classLoader'); Example Source: http://www.phpro.org/tutorials/SPL-Autoload.html
  • 7. Multiple Autoloaders <?php /*** nullify any existing autoloads ***/ spl_autoload_register(null, false); spl_autoload_register(array('Doctrine_Core', 'autoload')); spl_autoload_register(array('Doctrine_Core', 'modelsAutoload'));
  • 8. Multiple Autoloaders <?php class Doctrine_Core { public static function autoload($className) { if (strpos($className, 'sfYaml') === 0) { require dirname(__FILE__) . '/Parser/sfYaml/' . $className . '.php'; return true; } if (0 !== stripos($className, 'Doctrine_') || class_exists($className, false) || interface_exists($className, false)) { return false; } $class = self::getPath() . DIRECTORY_SEPARATOR . str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php'; if (file_exists($class)) { require $class; return true; } return false; }
  • 10. iterator_to_array • Takes an iterator object, an object that implements Traversable • All iterators implement Traversable
  • 11. spl_object_hash • MD5 hash of internal pointer • When objects are destroyed their object hash is released • Object Hash ID can/will be reused after destruction.
  • 13. ArrayObject • Allows objects to act like arrays • Does not allow usage of array functions on object • Built in methods: ksort, usort, asort, getArrayCopy
  • 14. SplFileInfo • Object that returns information on Files/ Folders • isDir, isFile, isReadable, isWritable, getPerms (returns int), etc. Example Source: http://us3.php.net/manual/en/class.splfileinfo.php
  • 15. SPL Interfaces • ArrayAccess • Iterator • RecursiveIterator • Countable • SeekableIterator • SplSubject/SplObserver
  • 16. Observer Pattern (SPL) • Great for applying hooks • Exception Handling • User Authentication
  • 17. SplSubject <?php class ExceptionHandler implements SplSubject { private $_observers = array(); public function attach(SplObserver $observer) { $id = spl_object_hash($observer); $this->_observers[$id] = $observer; } public function detach(SplObserver $observer) { $id = spl_object_hash($observer); unset($this->_observers[$id]); } public function notify() { foreach($this->_observers as $obs) { $obs->update($this); } } public function handle(Exception $e) { $this->exception = $e; $this->notify(); } } Example Source: http://devzone.zend.com/article/12229
  • 18. SplObserver Class Mailer implements SplObserver { public function update(SplSubject $subject) { // Do something with subject object } } // Create the ExceptionHandler $handler = new ExceptionHandler(); // Attach an Exception Logger and Mailer $handler->attach(new Mailer()); // Set ExceptionHandler::handle() as the default set_exception_handler(array($handler, 'handle')); Example Source: http://devzone.zend.com/article/12229
  • 19. ArrayAccess • OffsetExists - Values exists for key, returns boolean • OffsetSet - Set value for key • OffsetGet - Return value for key • OffsetUnset - Remove value from array • Note that if the array is numerically indexed, a call to array_values() will be required to re-index the array if that is the behaviour required. Example Source: http://www.phpro.org/tutorials/Introduction-to-SPL-ArrayAccess.html
  • 20. ArrayAccess Example <?php class book implements ArrayAccess { public $title; public $author; public $isbn; public function offsetExists( $offset ) { return isset( $this->$offset ); } public function offsetSet( $offset, $value) { $this->$offset = $value; } public function offsetGet( $offset ) { return $this->$offset; } public function offsetUnset( $offset ) { unset( $this->$offset ); } } Example Source: http://www.phpro.org/tutorials/Introduction-to-SPL-ArrayAccess.html
  • 21. Iterator • Provides basic iterator functionality (foreach) • Interface requires the following methods • current(), key(), next(), rewind(), valid()
  • 22. Recursive Iterator • A foreach only goes top level, but many times you need to dig deeper • Recursive Iterator extends Iterator and requires hasChildren() and getChildren()
  • 23. Countable • Internal Counter <?php class loopy { public function count() { static $count = 0; return $count++; } public function access() { $this->count(); // Method logic } }
  • 24. SeekableIterator • Other iterators must start at beginning of an array, but seekable allows you to change iteration start point. <?php class PartyMemberIterator implements SeekableIterator { public function seek($index) { $this->rewind(); $position = 0; while ($position < $index && $this->valid()) { $this->next(); $position++; } if (!$this->valid()) { throw new OutOfBoundsException('Invalid position'); } } Example Source: http://devzone.zend.com/article/2565
  • 25. SPL Iterators • ArrayIterator • LimitIterator • DirectoryIterator • RecursiveDirectoryIterator • GlobIterator
  • 26. ArrayIterator • Implements: Iterator, Traversable, ArrayAccess, SeekableIterator, Countable • Used to Iterate over ArrayObject or PHP array
  • 27. ArrayIterator <?php // Using While /*** create a new object ***/ $object = new ArrayIterator($array); /*** rewind to the beginning of the array ***/ $object->rewind(); /*** check for valid member ***/ while($object->valid()) { /*** echo the key and current value ***/ echo $object->key().' -&gt; '.$object->current().'<br />'; /*** hop to the next array member ***/ $object->next(); } // Using Foreach $object = new ArrayIterator($array); foreach($object as $key=>$value) { echo $key.' => '.$value.'<br />'; } Example Source: http://www.phpro.org/tutorials/Introduction-to-SPL.html#6
  • 28. LimitIterator • Used similar to Limit in SQL <?php // Show 10 files/folders starting from the 3rd. $offset = 3; $limit = 10; $filepath = '/var/www/vhosts/mysite/images' $it = new LimitIterator(new DirectoryIterator($filepath), $offset, $limit); foreach($it as $r) { // output the key and current array value echo $it->key().' -- '.$it->current().'<br />'; }
  • 29. DirectoryIterator • If you’re accessing the filesystem this is the iterator for you! • Returns SplFileInfo object
  • 30. DirectoryIterator <?php <?php $hdl = opendir('./'); try while ($dirEntry = readdir($hdl)) { { /*** class create new DirectoryIterator Object ***/ if (substr($dirEntry, 0, 1) != '.') foreach ( new DirectoryIterator('./') as $Item ) { { if(!is_file($dirEntry)) echo $Item.'<br />'; { } continue; } } /*** if an exception is thrown, catch it here ***/ $listing[] = $dirEntry; catch(Exception $e) } { } echo 'No files Found!<br />'; closedir($hdl); } foreach($listing as $my_file) { echo $my_file.'<br />'; }
  • 31. RecursiveDirectory Iterator • Move out of the top level and get all children files/folders <?php $dir = '/Users/jsmith/Sites/vhosts/test.local/wwwroot'; $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)); // could use CHILD_FIRST if you so wish foreach ($iterator as $file) { echo $file . "<br />"; }
  • 32. GlobIterator (5.3) • Very Similar to DirectoryIterator • Only use if you want to convert old glob code into an iterator object • returns SplFileInfo Objects
  • 33. SPL Exceptions • Logic Exception • RuntimeException • BadFunction • OutOfBounds • BadMethodCall • Range • InvalidArgument • UnexpectedValue • OutOfRange • Underflow Example Source: http://www.php.net/manual/en/spl.exceptions.php
  • 34. New SPL in PHP 5.3
  • 35. SplFixedArray • Array with pre-defined dimensions • Shows great speed for setting and retrieving • If you change Array dimensions, it will crawl.
  • 36. SplHeap • Automatically reorder after insert, based off of compare() method • Extract is similar to array_shift() • Great memory usage! Example Source: http://www.slideshare.net/tobias382/new-spl-features-in-php-53
  • 37. SplMaxHeap • Subclass of SplHeap • When you extract() a value it will return in order from greatest to least <?php $heap = new SplMaxHeap(); $heap->insert('b'); $heap->insert('a'); $heap->insert('c'); echo $heap->extract()."n"; echo $heap->extract()."n"; echo $heap->extract()."n"; // OUTPUT: // c // b // a Example Source: http://www.alberton.info/php_5.3_spl_data_structures.html
  • 38. SplMinHeap • Subclass of SplHeap • When you extract() a value it will return in order from least to greatest <?php $heap = new SplMinHeap(); $heap->insert('b'); $heap->insert('a'); $heap->insert('c'); echo $heap->extract()."n"; echo $heap->extract()."n"; echo $heap->extract()."n"; // OUTPUT: // a // b // c Example Source: http://www.alberton.info/php_5.3_spl_data_structures.html
  • 39. SplDoublyLinkedList • Do not know size of list/array • Can only be read sequentially • Less processing power required, on large data sets provides better memory usage
  • 40. SplStack • Method: push and pop • LIFO
  • 41. SplQueue • Methods: enqueue and dequeue • FIFO
  • 43. Useful Links • SPL in 5.3 • http://www.alberton.info/ php_5.3_spl_data_structures.html • http://www.slideshare.net/tobias382/new-spl-features-in- php-53 • Intro to SPL • http://www.phpro.org/tutorials/Introduction-to-SPL.html • http://www.slideshare.net/DragonBe/spl-not-a-bridge-too- far
  • 44. Thanks for listening! Contact Information [t]: @jakefolio [e]: jake@dallasphp.org [w]: http://www.jakefolio.com [irc]: #dallasphp