1. SPL, not a bridge too far
phpNW 2009 - Manchester
2. Who am I ?
Michelangelo van Dam
Independent Enterprise PHP consultant
Co-founder PHPBenelux UG
@dragonbe
http://dragonbe.com
2
3. Who are you ?
Are you familiar with php.net ?
Are you familiar with arrays ?
Are you familiar with OOP ?
Are you familiar with Design Patterns ?
3
4. What is SPL ?
Standard PHP Library
interfaces, classes and methods
solve common development challenges
Available since PHP 5.0 !!!
As of 5.3 SPL cannot be turned off from the source !
4
6. Definition of SPL
SPL provides a huge toolkit that assists you to easily
iterate over a diversity of data structures in a
standardized way
6
7. What does it provide ?
• ArrayObject - approach arrays as objects
• Iterators - various iterators
• Interfaces - iterator interfaces for your objects
• Exceptions - exceptions to streamline error handling
• SPL Functions - extra functions and autoloader func
• SplFileInfo - tools for filesystem access
• Data structures - structuring data sequences
7
9. ArrayObject
• provides an interface
- treat arrays as objects
- elements are iteratable
- provides serializing and deserializing of arrays
- sorting elements (w/ or w/o callback methods)
- exchange elements with other arrays or objects
9
12. …
More of ArrayObject
// serializing object for caching, sessions, …
$obj->serialize();
// adding more key/value elements to the stack
$obj->offsetSet('enterprise', 'Ivo Jansch');
// removing by key
$obj->offsetUnset('time');
…
12
13. Iterator
• provides a common interface
• to iterate over “things”
- xml data
- database data
- arrays
• move back and forth in a stack
• distinct methods to access keys and values
• specific iterators for different purposes
13
27. Flattened Array output
$iterator = new RecursiveArrayIterator(new ArrayObject($company));
$ritit = new RecursiveIteratorIterator($iterator);
foreach ($ritit as $key => $value) {
echo $key . ' = ' . $value . PHP_EOL;
}
// outputs
name = Chuck Norris
position = Account Manager
name = Jane Doe
position = Project Manager
name = Cinderella
position = Developer
name = Shrek
position = Graphical Designer
name = John Doe
position = Project Manager
27
28. Interfaces
• Countable: an internal counter
• OuterIterator: iteration over inner iterators
• RecursiveIterator: iterating in an recursive way
• SeekableIterator: an internal stack seeker
• SplObserver: implements observer pattern
• SplSubject: implements observer pattern
28
29. <?php
Interface example
// file: Order.php
class Order implements Countable, SplSubject
{
protected $_orders;
protected $_count;
public function __construct()
{
$this->_count = 0;
$this->_orders = array ();
}
public function placeOrder()
{
$this->_count++;
}
public function attach(SplObserver $observer)
{
$this->_orders[] = $observer;
}
public function detach(SplObserver $observer)
{
// not used in this case
}
29
30. Interface Example (2)
public function notify()
{
foreach ($this->_orders as $obj) {
$obj->update($this);
}
}
public function count()
{
return $this->_count;
}
}
<?php
// file: PlaceOrder.php
class PlaceOrder implements SplObserver
{
public function update(SplSubject $order)
{
echo 'We have ' . count($order) . ' orders now' . PHP_EOL;
}
}
30
31. Running Interface Example
<?php
require_once 'Order.php';
require_once 'PlaceOrder.php';
$order = new Order();
$placeOrder = new PlaceOrder();
$order->attach($placeOrder);
$order->notify();
$order->placeOrder();
$order->notify();
$order->placeOrder();
$order->notify();
$ php ./spl_observer.php
We have 0 orders now
We have 1 orders now
We have 2 orders now
31
35. <?php
Exceptions Example
//file: spl_exception01.php
class MyClass
{
public function giveANumberFromOneToTen($number)
{
if($number < 1 || $number > 10) {
throw new OutOfBoundsException('Number should be between 1 and 10');
}
echo $number . PHP_EOL;
}
}
$my = new MyClass();
try {
$my->giveANumberFromOneToTen(5);
$my->giveANumberFromOneToTen(20);
} catch (OutOfBoundsException $e) {
echo $e->getMessage() . PHP_EOL;
}
Output:
$ /usr/bin/php ./spl_exception01.php
5
Number should be between 1 and 10
35
36. SplFunctions
• functions for PHP and SPL in particular
• often dealing with auto loading
• some for internal referencing
36
37. <?php
SplFunctions Example
interface foo {}
interface bar {}
class baz implements foo, bar {}
class example extends baz {}
var_dump(class_implements(new baz));
var_dump(class_implements(new example));
37
40. <?php
SplFileInfo Example
// use the current file to get information from
$file = new SplFileInfo(dirname(__FILE__));
var_dump($file->isFile());
var_dump($file->getMTime());
var_dump($file->getSize());
var_dump($file->getFileInfo());
var_dump($file->getOwner());
//output
bool(false)
int(1244760945)
int(408)
object(SplFileInfo)#2 (0) {
}
int(501)
40
41. Processing CSV with SPL
Consider the following data.csv
Derick Rethans;time
Sebastian Bergmann;test
Marcus Börger;iterate
Ivo Jansch;enterprise
Matthew Weier O'Phinney;extend
Michelangelo van Dam;elephpant
41
42. <?php
SPL usage on CSV
$info = new SplFileInfo('data.csv');
if ($info->isReadable()) {
$file = $info->openFile();
$file->setFlags(SplFileObject::READ_CSV);
$file->setCsvControl(';','"');
foreach ($file as $row) {
list ($user, $term) = $row;
if (null !== $user && null !== $term) {
echo $user . ' is known for ' . $term . PHP_EOL;
}
}
}
//outputs
Derick Rethans is known for time
Sebastian Bergmann is known for test
Marcus Börger is known for iterate
Ivo Jansch is known for enterprise
Matthew Weier O'Phinney is known for extend
Michelangelo van Dam is known for elephpant
42
43. Data Structures
• Available in PHP 5.3.x
- SplDoublyLinkedList
✓ SplStack
✓ SplQueue
✓ SplHeap
✓ SplMaxHeap
✓ SplMinHeap
✓ SplPriorityQueue
43
49. Conclusion
SPL can help you solve common PHP issues
it’s built-in, so why not use it
it requires no “advanced skills” to use
49
50. SPL is not all good
• Matthew “Elazar” Turland pointed out:
- Performance could be better (SPLStack)
- ArrayObject doesn’t support all array
functions
• See his presentation:
http://ishouldbecoding.com/publications
50
53. Documentation problem
• php.net/spl needs more documentation !
• you can help on that part:
- see http://elizabethmariesmith.com/2009/02/setting-up-phd-on-windows
- you can set up phpdoc on each platform !
- Efnet: #php.doc channel
- http://doc.php.net - phpdoc@php.net
53
54. More about SPL...
• main SPL documentation:
http://php.net/spl
• PHPro Tutorials on SPL:
http://www.phpro.org/tutorials/Introduction-to-SPL.html
• Lorenzo Alberton’s blog:
http://www.alberton.info/php_5.3_spl_data_structures.html
• http://www.colder.ch/news/01-08-2009/34/splobjectstorage-for-
a-fa.html
54
55. License
This presentation is released under the Creative Commons
Attribution-Share Alike 3.0 Unported License
You are free:
- to share : to copy, distribute and transmit the work
- to remix : to adapt the work
Under the following conditions:
- attribution : You must attribute the work in the manner specified by the author or licensor
- share alike : If you alter, transform, or build upon this work, you may distribute the resulting work
only under the same, similar or a compatible license
See: http://creativecommons.org/licenses/by-sa/3.0/
55
56. Photo credits
Marcus Boerger - Sebastian Bergmann
http://www.flickr.com/photos/sebastian_bergmann/173891817
Golden Gate Bridge - Felix De Vliegher
http://www.flickr.com/photos/felixdv/2883471022/
56
57. Thank you
Find my slides on
http://slideshare.net/DragonBe
Don’t forget to vote !
http://joind.in/613
57
Hinweis der Redaktion
Promotion of SPL
now everyone uses PHP 5.3 for new projects, right ?
Created by Marcus Boerger
Created by Marcus Boerger
Definition of SPL
SPL functions
- base class functions
- autoloading functions
- looking at phpinfo() for PHP 5.3
- 6 interfaces
- 39 classes
easiest way converting array into an object
blue code is a lambda or anonymous function used in PHP 5.3
More info found on http://php.net/spl
arrays are stored as a whole in memory
iterators just the element that has focus
interface: design by contract for classes
example using SplObserver, SplSubject and Countable interface
definition from php.net
SplInfo provides a lot of details about a given file
work with lots of CSV data files
using a data model, makes things a whole lot easier
let&#x2019;s start of simple, using the SplStack here
simple example processing test results
modify the compare method to use the values of a given array
Soccer != football, but you get the point here, right ?
so, once you know how, it&#x2019;s not a bridge too far