SlideShare a Scribd company logo
1 of 38
Download to read offline
SPL
2
Who am I?
• Lorna Jane Mitchell
• PHP consultant, trainer, and writer
• Personal site at lornajane.net
• Twitter: @lornajane
• PHPNW regular!
3
SPL
• Standard PHP Library
• An extension to do common things
• FAST! Because it's in C
• Lots of functionality (tonight is just a
taster)
4
The SPL Drinking Game
• When anyone says "iterator", take a drink
http://www.flickr.com/photos/petereed/2667835909/
5
Before We Go …
• SPL relies heavily on OOP theory and
interfaces
• Let's recap on some theory
6
OOP
7
Classes vs Objects
• If the class is the recipe …
• Then the object is
the cake
1 <?php
2
3 class CupCake
4 {
5 public function addFrosting($colour, $height)
{
6 // ...
7 }
8 }
9
10 $cupcake = new CupCake();
11 var_dump($cupcake);
http://www.flickr.com/photos/quintanaroo/339856554/
8
Inheritance
• Using classes as "big-picture templates"
and changing details
• Parent has shared code
• Child contains differences
Cake
BirthdayCake CupCake
9
Example: Cake Class
1 <?php
2
3 class Cake
4 {
5 public function getIngredients() {
6 return array("2 eggs", "margarine", "sugar", "flour");
7 }
8 }
10
Example: CupCake Class
1 <?php
2
3 class CupCake
4 {
5 public function addFrosting($colour, $height)
{
6 // ...
7 }
8 }
9
10 $cupcake = new CupCake();
11 var_dump($cupcake);
11
Interfaces
• Define a contract
• Classes implement interfaces - they must
fulfil the contract
• Interfaces define a standard API and
ensure all providers implement it fully
12
Interface Example
1 <?php
2
3
4 interface Audible {
5 function speak();
6 }
7
8 class Sheep implements Audible {
9 function speak() {
10 echo "baaa!";
11 }
12 }
13
14 $animal = new Sheep();
15 if($animal instanceOf Audible) {
16 $animal->speak();
17 } else {
18 echo "*stares blankly*";
19 }
Example taken from http://thinkvitamin.com/code/oop-with-php-finishing-touches/
13
Object Comparison
• Check object types
– type hinting
– instanceOf operator
• Evaluate as true if object either:
– is of that type
– extends that type
– implements that type
14
SPL Interfaces
15
SPL Interfaces
• Countable
• ArrayAccess
• Iterator
16
Countable
• We can dictate what happens when we
count($object)
• Class implements Countable
• Class must now include a method called
count()
17
Countable Example
1 <?php
2
3 class Basket implements Countable
4 {
5 public $items = array();
6
7 public function addItem($item) {
8 $this->items[] = $item;
9 return true;
10 }
11
12 public function count() {
13 return count($this->items);
14 }
15 }
16
http://www.flickr.com/photos/dunbargardens/3740493102/
18
ArrayAccess
• Define object's array behaviour
• Allows us to use array notation with an
object in a special way
• A good example is SimpleXML, allows
array notation to access attributes
19
ArrayAccess
1 <?xml version="1.0" ?>
2 <foodStore>
3 <fridge>
4 <eggs />
5 <milk expiry="2010-11-07" />
6 </fridge>
7 <cupboard>
8 <flour expire="2010-08-31" />
9 </cupboard>
10 </foodStore>
1 <?php
2
3 $xml = simplexml_load_file('foodstore.xml');
4
5 echo $xml->fridge->milk['expiry'];
20
Iterators
• Dictate how we traverse an object when
looping
• Defines 5 methods:
1 <?php
2
3 interface Iterator
4 {
5 public function key();
6 public function current();
7 public function next();
8 public function valid();
9 public function rewind();
10 }
21
More Iterators
• DirectoryIterator
• LimitIterator
• SimpleXMLIterator
• CachingIterator
• ...
• RecursiveIteratorIterator
22
Using SPL
23
Using SPL
• SPL builds on these ideas to give us great
things
• Datastructures
• Filesystem handling
• SPLException
24
Datastructures
25
SPLFixedArray
• An object that behaves like an array
• Fixed length
• Integer keys only
• FAST!!
26
SPLDoublyLinkedList
• Simple and useful computer science
concept
• Ready-to-use implementation
• Can push, pop, iterate …
27
SPLStack, SPLQueue
• Built on the SPLDoublyLinkedList
• No need to home-spin these solutions in
PHP
• Simply extend the SPL ones
28
SPLQueue Example
1 <?php
2
3 class LornaList extends SPLQueue
4 {
5 public function putOnList($item) {
6 $this->enqueue($item);
7 }
8
9 public function getNext() {
10 // FIFO buffer, just gets whatever is oldest
11 $this->dequeue($item);
12 }
13 }
14
15 $todo_list = new LornaList();
16
17 // procastinate! Write the list
18 $todo_list->putOnList("write SPL talk");
19 $todo_list->putOnList("wrestle inbox");
20 $todo_list->putOnList("clean the house");
21
22 // Time to do stuff
23 $task = $todo_list->getNext();
24 echo $task;
Filesystem Handling
30
Filesystem Handling
• SPLFileInfo - everything you ever needed
to know about a file
• DirectoryIterator - very neat way of
working with directories and files
• DirectoryIterator returns individual items
of type SPLFileInfo
31
Filesystem Example
• taken directly from devzone
– http://devzone.zend.com/article/2565-The-Standard-PHP-Library-SPL
1 <?php
2
3 $path = new DirectoryIterator('/path/to/dir');
4
5 foreach ($path as $file) {
6 echo $file->getFilename() . "t";
7 echo $file->getSize() . "t";
8 echo $file->getOwner() . "t";
9 echo $file->getMTime() . "n";
10 }
32
Exceptions
33
SPLException
• Many additional exception types
• Allows us to throw (and catch) specific
exceptions
• Including:
– BadMethodCallException
– InvalidArgumentException
– RuntimeException
– OverflowException
34
SPL Exception Example
1 <?php
2
3 class LornaList extends SPLQueue
4 {
5 public function putOnList($item) {
6 if($this->count() > 40) {
7 throw new OverflowException(
8 'Seriously? This is never going to get done'
9 );
10 } else {
11 $this->enqueue($item);
12 }
13 }
14
15 public function getNext() {
16 // FIFO buffer, just gets whatever is oldest
17 $this->dequeue($item);
18 }
19 }
20
35
SPL
36
SPL
• Interfaces
• Datastructures
• File handling
• Exceptions
• … and so much more
37
Questions?
38
Resources
• PHP Manual
http://uk2.php.net/manual/en/book.spl.php
• DevZone Tutorial
http://devzone.zend.com/article/2565-The-Standard-PHP-Library-SPL
• PHPPro Article
http://www.phpro.org/tutorials/Introduction-to-SPL.html

More Related Content

Similar to SPL Primer

06-classes.ppt (copy).pptx
06-classes.ppt (copy).pptx06-classes.ppt (copy).pptx
06-classes.ppt (copy).pptxThắng It
 
SPL: The Undiscovered Library - DataStructures
SPL: The Undiscovered Library -  DataStructuresSPL: The Undiscovered Library -  DataStructures
SPL: The Undiscovered Library - DataStructuresMark Baker
 
Drupal 8: A story of growing up and getting off the island
Drupal 8: A story of growing up and getting off the islandDrupal 8: A story of growing up and getting off the island
Drupal 8: A story of growing up and getting off the islandAngela Byron
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation TutorialLorna Mitchell
 
Module 01 Stack and Recursion
Module 01 Stack and RecursionModule 01 Stack and Recursion
Module 01 Stack and RecursionTushar B Kute
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHPLorna Mitchell
 
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code styleRuby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code styleAnton Shemerey
 
OOP is more than Cars and Dogs
OOP is more than Cars and Dogs OOP is more than Cars and Dogs
OOP is more than Cars and Dogs Chris Tankersley
 
REST APIs in Laravel 101
REST APIs in Laravel 101REST APIs in Laravel 101
REST APIs in Laravel 101Samantha Geitz
 
Powershell Training
Powershell TrainingPowershell Training
Powershell TrainingFahad Noaman
 

Similar to SPL Primer (20)

06-classes.ppt (copy).pptx
06-classes.ppt (copy).pptx06-classes.ppt (copy).pptx
06-classes.ppt (copy).pptx
 
SPL: The Undiscovered Library - DataStructures
SPL: The Undiscovered Library -  DataStructuresSPL: The Undiscovered Library -  DataStructures
SPL: The Undiscovered Library - DataStructures
 
Drupal 8: A story of growing up and getting off the island
Drupal 8: A story of growing up and getting off the islandDrupal 8: A story of growing up and getting off the island
Drupal 8: A story of growing up and getting off the island
 
SQL Devlopment for 10 ppt
SQL Devlopment for 10 pptSQL Devlopment for 10 ppt
SQL Devlopment for 10 ppt
 
Modern php
Modern phpModern php
Modern php
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation Tutorial
 
laravel-53
laravel-53laravel-53
laravel-53
 
Slides
SlidesSlides
Slides
 
Module 01 Stack and Recursion
Module 01 Stack and RecursionModule 01 Stack and Recursion
Module 01 Stack and Recursion
 
PHP for hacks
PHP for hacksPHP for hacks
PHP for hacks
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHP
 
OOPs Concept
OOPs ConceptOOPs Concept
OOPs Concept
 
Php introduction
Php introductionPhp introduction
Php introduction
 
2009-02 Oops!
2009-02 Oops!2009-02 Oops!
2009-02 Oops!
 
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code styleRuby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
 
Lecture9_OOPHP_SPring2023.pptx
Lecture9_OOPHP_SPring2023.pptxLecture9_OOPHP_SPring2023.pptx
Lecture9_OOPHP_SPring2023.pptx
 
OOP is more than Cars and Dogs
OOP is more than Cars and Dogs OOP is more than Cars and Dogs
OOP is more than Cars and Dogs
 
Code smells in PHP
Code smells in PHPCode smells in PHP
Code smells in PHP
 
REST APIs in Laravel 101
REST APIs in Laravel 101REST APIs in Laravel 101
REST APIs in Laravel 101
 
Powershell Training
Powershell TrainingPowershell Training
Powershell Training
 

More from Lorna Mitchell

Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP TutorialLorna Mitchell
 
Git, GitHub and Open Source
Git, GitHub and Open SourceGit, GitHub and Open Source
Git, GitHub and Open SourceLorna Mitchell
 
Business 101 for Developers: Time and Money
Business 101 for Developers: Time and MoneyBusiness 101 for Developers: Time and Money
Business 101 for Developers: Time and MoneyLorna Mitchell
 
Things I wish web graduates knew
Things I wish web graduates knewThings I wish web graduates knew
Things I wish web graduates knewLorna Mitchell
 
Teach a Man To Fish (phpconpl edition)
Teach a Man To Fish (phpconpl edition)Teach a Man To Fish (phpconpl edition)
Teach a Man To Fish (phpconpl edition)Lorna Mitchell
 
Tool Up Your LAMP Stack
Tool Up Your LAMP StackTool Up Your LAMP Stack
Tool Up Your LAMP StackLorna Mitchell
 
Understanding Distributed Source Control
Understanding Distributed Source ControlUnderstanding Distributed Source Control
Understanding Distributed Source ControlLorna Mitchell
 
Best Practice in Web Service Design
Best Practice in Web Service DesignBest Practice in Web Service Design
Best Practice in Web Service DesignLorna Mitchell
 
Coaching Development Teams: Teach A Man To Fish
Coaching Development Teams: Teach A Man To FishCoaching Development Teams: Teach A Man To Fish
Coaching Development Teams: Teach A Man To FishLorna Mitchell
 
Implementing OAuth with PHP
Implementing OAuth with PHPImplementing OAuth with PHP
Implementing OAuth with PHPLorna Mitchell
 
Could You Telecommute?
Could You Telecommute?Could You Telecommute?
Could You Telecommute?Lorna Mitchell
 
Running a Project with Github
Running a Project with GithubRunning a Project with Github
Running a Project with GithubLorna Mitchell
 
27 Ways To Be A Better Developer
27 Ways To Be A Better Developer27 Ways To Be A Better Developer
27 Ways To Be A Better DeveloperLorna Mitchell
 

More from Lorna Mitchell (20)

OAuth: Trust Issues
OAuth: Trust IssuesOAuth: Trust Issues
OAuth: Trust Issues
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP Tutorial
 
Git, GitHub and Open Source
Git, GitHub and Open SourceGit, GitHub and Open Source
Git, GitHub and Open Source
 
Business 101 for Developers: Time and Money
Business 101 for Developers: Time and MoneyBusiness 101 for Developers: Time and Money
Business 101 for Developers: Time and Money
 
Things I wish web graduates knew
Things I wish web graduates knewThings I wish web graduates knew
Things I wish web graduates knew
 
Teach a Man To Fish (phpconpl edition)
Teach a Man To Fish (phpconpl edition)Teach a Man To Fish (phpconpl edition)
Teach a Man To Fish (phpconpl edition)
 
Web services tutorial
Web services tutorialWeb services tutorial
Web services tutorial
 
Join In With Joind.In
Join In With Joind.InJoin In With Joind.In
Join In With Joind.In
 
Tool Up Your LAMP Stack
Tool Up Your LAMP StackTool Up Your LAMP Stack
Tool Up Your LAMP Stack
 
Going Freelance
Going FreelanceGoing Freelance
Going Freelance
 
Understanding Distributed Source Control
Understanding Distributed Source ControlUnderstanding Distributed Source Control
Understanding Distributed Source Control
 
Best Practice in Web Service Design
Best Practice in Web Service DesignBest Practice in Web Service Design
Best Practice in Web Service Design
 
Coaching Development Teams: Teach A Man To Fish
Coaching Development Teams: Teach A Man To FishCoaching Development Teams: Teach A Man To Fish
Coaching Development Teams: Teach A Man To Fish
 
Implementing OAuth with PHP
Implementing OAuth with PHPImplementing OAuth with PHP
Implementing OAuth with PHP
 
Web Services Tutorial
Web Services TutorialWeb Services Tutorial
Web Services Tutorial
 
Example Presentation
Example PresentationExample Presentation
Example Presentation
 
Could You Telecommute?
Could You Telecommute?Could You Telecommute?
Could You Telecommute?
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Running a Project with Github
Running a Project with GithubRunning a Project with Github
Running a Project with Github
 
27 Ways To Be A Better Developer
27 Ways To Be A Better Developer27 Ways To Be A Better Developer
27 Ways To Be A Better Developer
 

Recently uploaded

SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
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
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
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
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
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
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 

Recently uploaded (20)

SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
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
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
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
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
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
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 

SPL Primer

  • 1. SPL
  • 2. 2 Who am I? • Lorna Jane Mitchell • PHP consultant, trainer, and writer • Personal site at lornajane.net • Twitter: @lornajane • PHPNW regular!
  • 3. 3 SPL • Standard PHP Library • An extension to do common things • FAST! Because it's in C • Lots of functionality (tonight is just a taster)
  • 4. 4 The SPL Drinking Game • When anyone says "iterator", take a drink http://www.flickr.com/photos/petereed/2667835909/
  • 5. 5 Before We Go … • SPL relies heavily on OOP theory and interfaces • Let's recap on some theory
  • 7. 7 Classes vs Objects • If the class is the recipe … • Then the object is the cake 1 <?php 2 3 class CupCake 4 { 5 public function addFrosting($colour, $height) { 6 // ... 7 } 8 } 9 10 $cupcake = new CupCake(); 11 var_dump($cupcake); http://www.flickr.com/photos/quintanaroo/339856554/
  • 8. 8 Inheritance • Using classes as "big-picture templates" and changing details • Parent has shared code • Child contains differences Cake BirthdayCake CupCake
  • 9. 9 Example: Cake Class 1 <?php 2 3 class Cake 4 { 5 public function getIngredients() { 6 return array("2 eggs", "margarine", "sugar", "flour"); 7 } 8 }
  • 10. 10 Example: CupCake Class 1 <?php 2 3 class CupCake 4 { 5 public function addFrosting($colour, $height) { 6 // ... 7 } 8 } 9 10 $cupcake = new CupCake(); 11 var_dump($cupcake);
  • 11. 11 Interfaces • Define a contract • Classes implement interfaces - they must fulfil the contract • Interfaces define a standard API and ensure all providers implement it fully
  • 12. 12 Interface Example 1 <?php 2 3 4 interface Audible { 5 function speak(); 6 } 7 8 class Sheep implements Audible { 9 function speak() { 10 echo "baaa!"; 11 } 12 } 13 14 $animal = new Sheep(); 15 if($animal instanceOf Audible) { 16 $animal->speak(); 17 } else { 18 echo "*stares blankly*"; 19 } Example taken from http://thinkvitamin.com/code/oop-with-php-finishing-touches/
  • 13. 13 Object Comparison • Check object types – type hinting – instanceOf operator • Evaluate as true if object either: – is of that type – extends that type – implements that type
  • 15. 15 SPL Interfaces • Countable • ArrayAccess • Iterator
  • 16. 16 Countable • We can dictate what happens when we count($object) • Class implements Countable • Class must now include a method called count()
  • 17. 17 Countable Example 1 <?php 2 3 class Basket implements Countable 4 { 5 public $items = array(); 6 7 public function addItem($item) { 8 $this->items[] = $item; 9 return true; 10 } 11 12 public function count() { 13 return count($this->items); 14 } 15 } 16 http://www.flickr.com/photos/dunbargardens/3740493102/
  • 18. 18 ArrayAccess • Define object's array behaviour • Allows us to use array notation with an object in a special way • A good example is SimpleXML, allows array notation to access attributes
  • 19. 19 ArrayAccess 1 <?xml version="1.0" ?> 2 <foodStore> 3 <fridge> 4 <eggs /> 5 <milk expiry="2010-11-07" /> 6 </fridge> 7 <cupboard> 8 <flour expire="2010-08-31" /> 9 </cupboard> 10 </foodStore> 1 <?php 2 3 $xml = simplexml_load_file('foodstore.xml'); 4 5 echo $xml->fridge->milk['expiry'];
  • 20. 20 Iterators • Dictate how we traverse an object when looping • Defines 5 methods: 1 <?php 2 3 interface Iterator 4 { 5 public function key(); 6 public function current(); 7 public function next(); 8 public function valid(); 9 public function rewind(); 10 }
  • 21. 21 More Iterators • DirectoryIterator • LimitIterator • SimpleXMLIterator • CachingIterator • ... • RecursiveIteratorIterator
  • 23. 23 Using SPL • SPL builds on these ideas to give us great things • Datastructures • Filesystem handling • SPLException
  • 25. 25 SPLFixedArray • An object that behaves like an array • Fixed length • Integer keys only • FAST!!
  • 26. 26 SPLDoublyLinkedList • Simple and useful computer science concept • Ready-to-use implementation • Can push, pop, iterate …
  • 27. 27 SPLStack, SPLQueue • Built on the SPLDoublyLinkedList • No need to home-spin these solutions in PHP • Simply extend the SPL ones
  • 28. 28 SPLQueue Example 1 <?php 2 3 class LornaList extends SPLQueue 4 { 5 public function putOnList($item) { 6 $this->enqueue($item); 7 } 8 9 public function getNext() { 10 // FIFO buffer, just gets whatever is oldest 11 $this->dequeue($item); 12 } 13 } 14 15 $todo_list = new LornaList(); 16 17 // procastinate! Write the list 18 $todo_list->putOnList("write SPL talk"); 19 $todo_list->putOnList("wrestle inbox"); 20 $todo_list->putOnList("clean the house"); 21 22 // Time to do stuff 23 $task = $todo_list->getNext(); 24 echo $task;
  • 30. 30 Filesystem Handling • SPLFileInfo - everything you ever needed to know about a file • DirectoryIterator - very neat way of working with directories and files • DirectoryIterator returns individual items of type SPLFileInfo
  • 31. 31 Filesystem Example • taken directly from devzone – http://devzone.zend.com/article/2565-The-Standard-PHP-Library-SPL 1 <?php 2 3 $path = new DirectoryIterator('/path/to/dir'); 4 5 foreach ($path as $file) { 6 echo $file->getFilename() . "t"; 7 echo $file->getSize() . "t"; 8 echo $file->getOwner() . "t"; 9 echo $file->getMTime() . "n"; 10 }
  • 33. 33 SPLException • Many additional exception types • Allows us to throw (and catch) specific exceptions • Including: – BadMethodCallException – InvalidArgumentException – RuntimeException – OverflowException
  • 34. 34 SPL Exception Example 1 <?php 2 3 class LornaList extends SPLQueue 4 { 5 public function putOnList($item) { 6 if($this->count() > 40) { 7 throw new OverflowException( 8 'Seriously? This is never going to get done' 9 ); 10 } else { 11 $this->enqueue($item); 12 } 13 } 14 15 public function getNext() { 16 // FIFO buffer, just gets whatever is oldest 17 $this->dequeue($item); 18 } 19 } 20
  • 36. 36 SPL • Interfaces • Datastructures • File handling • Exceptions • … and so much more
  • 38. 38 Resources • PHP Manual http://uk2.php.net/manual/en/book.spl.php • DevZone Tutorial http://devzone.zend.com/article/2565-The-Standard-PHP-Library-SPL • PHPPro Article http://www.phpro.org/tutorials/Introduction-to-SPL.html