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

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 

Recently uploaded (20)

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 

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