SPL: The Missing Link in Development
Jake Smith
Dallas PHP - 7/13/2010
Slide 2
Slide 2 text
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/
Slide 3
Slide 3 text
SPL Background
• Provides Interfaces, Classes and Functions
• As of PHP 5.3 you can not turn off SPL
• Poor documentation root of poor
adoption.
Slide 4
Slide 4 text
SPL Autoloading
Slide 5
Slide 5 text
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');
}
}
_name = $name;
$this->_attrs = $attrs;
}
Class Name
Slide 6
Slide 6 text
Autoloading w/SPL
Slide 7
Slide 7 text
Multiple Autoloaders
Slide 8
Slide 8 text
Multiple Autoloaders
Slide 9
Slide 9 text
SPL Functions
Slide 10
Slide 10 text
iterator_to_array
• Takes an iterator object, an object that
implements Traversable
• All iterators implement Traversable
Slide 11
Slide 11 text
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.
Slide 12
Slide 12 text
SPL Classes
• ArrayObject
• SplFileInfo
Slide 13
Slide 13 text
ArrayObject
• Allows objects to act like arrays
• Does not allow usage of array functions on
object
• Built in methods: ksort, usort, asort,
getArrayCopy
Slide 14
Slide 14 text
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
Observer Pattern (SPL)
• Great for applying hooks
• Exception Handling
• User Authentication
Slide 17
Slide 17 text
SplSubject
_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
Slide 18
Slide 18 text
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
Slide 19
Slide 19 text
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
Slide 20
Slide 20 text
ArrayAccess Example
$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
Slide 21
Slide 21 text
Iterator
• Provides basic iterator functionality
(foreach)
• Interface requires the following methods
• current(), key(), next(), rewind(), valid()
Slide 22
Slide 22 text
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()
SeekableIterator
• Other iterators must start at beginning of
an array, but seekable allows you to change
iteration start point.
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
ArrayIterator
• Implements: Iterator, Traversable,
ArrayAccess, SeekableIterator, Countable
• Used to Iterate over ArrayObject or PHP
array
Slide 27
Slide 27 text
ArrayIterator
rewind();
/*** check for valid member ***/
while($object->valid())
{
/*** echo the key and current value ***/
echo $object->key().' -> '.$object->current().' ';
/*** hop to the next array member ***/
$object->next();
}
// Using Foreach
$object = new ArrayIterator($array);
foreach($object as $key=>$value)
{
echo $key.' => '.$value.' ';
}
Example Source: http://www.phpro.org/tutorials/Introduction-to-SPL.html#6
Slide 28
Slide 28 text
LimitIterator
• Used similar to Limit in SQL
key().' -- '.$it->current().' ';
}
Slide 29
Slide 29 text
DirectoryIterator
• If you’re accessing the filesystem this is the
iterator for you!
• Returns SplFileInfo object
Slide 30
Slide 30 text
DirectoryIterator
';
}
';
}
}
/*** if an exception is thrown, catch it here ***/
catch(Exception $e)
{
echo 'No files Found! ';
}
Slide 31
Slide 31 text
RecursiveDirectory
Iterator
• Move out of the top level and get all
children files/folders
";
}
Slide 32
Slide 32 text
GlobIterator (5.3)
• Very Similar to DirectoryIterator
• Only use if you want to convert old glob
code into an iterator object
• returns SplFileInfo Objects
SplFixedArray
• Array with pre-defined dimensions
• Shows great speed for setting and
retrieving
• If you change Array dimensions, it will
crawl.
Slide 36
Slide 36 text
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
Slide 37
Slide 37 text
SplMaxHeap
• Subclass of SplHeap
• When you extract() a value it will return in
order from greatest to least
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
Slide 38
Slide 38 text
SplMinHeap
• Subclass of SplHeap
• When you extract() a value it will return in
order from least to greatest
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
Slide 39
Slide 39 text
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
Slide 40
Slide 40 text
SplStack
• Method: push and pop
• LIFO
Slide 41
Slide 41 text
SplQueue
• Methods: enqueue and dequeue
• FIFO
Slide 42
Slide 42 text
Questions?
Slide 43
Slide 43 text
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
Slide 44
Slide 44 text
Thanks for listening!
Contact Information
[t]: @jakefolio
[e]: [email protected]
[w]: http://www.jakefolio.com
[irc]: #dallasphp