SlideShare a Scribd company logo
1 of 32
Download to read offline
May the 4th
PHP CollectionsImage by statefarm
• Object Relationships…
• Perfect for One-To-Many Joins…
• Traditionally just arrays which were good…
WHY?
• No rules about what is stored in the array…
• No rules about how to store/retrieve…
• Often public…
• No separation of concerns…
• Arrays are by default passed byValue…
• Array[‘Notation’]…
WHATS WRONG WITH ARRAYS?
• Easy to use…
• Easy to add, access, remove items…
• Easy to traverse/loop…
• How many array_ functions are there?…
WHAT WAS RIGHT WITH ARRAYS?
• It’s a “bucket” of objects
• So, essentially, it’s a wrapper for an array…
• But encapsulated with rules…
• We can control the indexes…
• We know more about the content types…
• It can have non-member properties
WHAT IS A COLLECTION CLASS?
• private $items = array(); // property…
• traversable…
• countable…
• Other Interfaces?

e.g. JsonSerializable() or toJSON()
ATTRIBUTES OF A COLLECTION CLASS
• Arrays are mutable…
• Collection Classes are often mutable…
• mutability is a choice to be made early on…
• The Immutable class is lightweight…
MUTABILITY
• with function addItem(FixedType $item){}…
• we now have type checking
• adding individual elements
MUTABILITY &TYPE CHECKING
• Only one way an object can be immutable…

• __construct($items){

					$this->items	=	$items

}	
• It is fixed after instantiation, no setItems / addItems
methods…
IMMUTABILITY &TYPE CHECKING
SOME CODE
// the old way

Class Artist {



public $albums = array();



private $name;



public function __construct($name) {

$this->name = $name;

}



}



$artist = new Artist('Prince');

$artist->albums[] = '1999';

$artist->albums[] = 'Purple Rain';

Class Artist {



private $albums = array();



private $name;



public function __construct($name) {

$this->name = $name;

}



public function addItem($item) {

$this->albums[] = $item;

}



}



$artist = new Artist('Prince');

$artist->addItem[] = 'Purple Rain';
Class Artist {



/**

* @var AlbumCollection

*/

private $albums;





public function setAlbums($albums)

{

$this->albums = $albums;

}



//...

}





Class AlbumCollection {



private $items = array();



public function addItem(Album $album) {

$this->items[] = $album;

}



}
// Using the Collection Class


$artist = new Artist('Prince');



// Build The Album Collection

$albums = new AlbumCollection();
// Note we add Album types

$albums->addItem( new Album('1999') );

$albums->addItem( new Album(‘Purple Rain') );

$albums->addItem( new Album(‘Sign O The Times') );



// Set the Collection as an Artist property

$artist->setAlbums($albums);
WHAT ABOUT

COUNTABLE 

TRAVERSABLE

…
Class AlbumCollection implements IteratorAggregate ,
Countable {



private $items = array();



public function addItem(Album $album) {

$this->items[] = $album;

}



// Implement Traversable (Iterator Aggregate) 

// Interface

public function getIterator() {

return new ArrayIterator($this->items);

}



// Implement Countable Interface

public function count() {

return count($this->items);

}



}
• Our app will contain more than one collection…
• Remember DRY principles…
• Don’t copy/paste the interface implementations…
ABSTRACT FOR PORTABLITY
abstract Class BaseCollection implements
Countable, IteratorAggregate 

{

private $items = array();



// Implement Traversable via
// IteratorAggregate Interface

public function getIterator() {

return new ArrayIterator($this->items);

}



// Implement Countable Interface

public function count() {

return count($this->items);

}



}

// An Artist has many Albums

Class AlbumCollection extends BaseCollection {



private $items = array();



public function addItem(Album $album) {

$this->items[] = $album;

}



}



// Albums have many Songs

Class SongCollection extends BaseCollection {



private $items = array();



public function addItem(Song $song) {

$this->items[] = $song;

}



}
class Artist {



// @var AlbumCollection

protected $albums;



// @var SongCollection

protected $songs;



// @var TourCollection

protected $concerts;



// MetadataCollection

protected $metadata;



// GenreCollection;

protected $genres;



// Tags Collection

protected $tags;



}
COLLECTING THE DOTS…



WHAT ABOUTTHE DOTS..?
• Pass an indeterminate number of parameters…
• Can pack a list of arguments…
• Can unpack an array to a list of arguments…
• Can be used in the function call or definition…
• So…
PHP5.6+ HASTHE …TOKEN

THEVARIABLE LENGTHTOKEN
bit.ly/VarL3nT0k
WITH IT WE CAN CREATE

STRONGLY TYPED ARRAYS


Class AlbumCollection extends BaseCollection {



private $items = array();
// Strongly typed, unknown length
// All items passed must be of type Album
public function __construct(Album ...$albums)

{

$this->items = $albums;

}



}



$batman = new Album('Batman');

$purple = new Album('Purple Rain’);
// this works, but it’s messy

$albums = new AlbumCollection($batman, $purple);



Class AlbumCollection extends BaseCollection {



//…



}

// we can create an array of Albums

// or foreach through a DB powered list
$Albums[] = new Album('Batman');

$Albums[] = new Album('Purple Rain’);
$Albums[] = new Album('Dirty Mind');

$Albums[] = new Album('Diamonds and Pearls');

// this wont work

$collection = new AlbumCollection($Albums);

// this WILL work, using ‘…’ to unpack the Array

$collection = new AlbumCollection(…$Albums);

• We are now portable thanks to our abstract
collection
• We are strongly typed
• We are decoupled, each type and collection can
be independently tested
PORTABLE &TESTABLE
• IteratorAggregate Interface as a minimum
• extend ArrayObject

implements IteratorAggregate,ArrayAccess, Serializable, Countable
• Only implement the functionality that you 

will use/need
USETHE SPL…
• Add commonly used functionlaity to your base
class
• e.g. findBy($property,	$value)

BUILD ONYOUR BASE
public function findBy($property, $value)

{

// look for an accessor method e.g. getTitle()
$method = “get" . ucwords($property);
foreach ($this->items as $key => $obj) {
if (method_exists($obj, $method) {
if ($obj->{$method}() == $property) {
return($obj);
}
}
}


}
BUILD ONYOUR CONCRETE CLASS


Class SongCollection extends BaseCollection {



protected $items;



// each song has a duration, 

// collection has a total duration

private $totalDuration;



public function getTotalDuration()

{

$totalDuration= 0;

foreach($this->items as $song) {

$totalDuration += $song->duration;

}

}



}
• Many Frameworks, especially ORM components
have their own Collection implementations
• If you use a Framework investigate the options

Doctrine ArrayCollection, IlluminateSupportCollection
• If you aren’t using a framework…

…Learn from the Frameworks
A FINAL WORD ON FRAMEWORKS
T H A N K Y O U

More Related Content

What's hot

The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of LithiumNate Abele
 
Php Using Arrays
Php Using ArraysPhp Using Arrays
Php Using Arraysmussawir20
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of LithiumNate Abele
 
Laravel collections an overview - Laravel SP
Laravel collections an overview - Laravel SPLaravel collections an overview - Laravel SP
Laravel collections an overview - Laravel SPMatheus Marabesi
 
Refactoring using Codeception
Refactoring using CodeceptionRefactoring using Codeception
Refactoring using CodeceptionJeroen van Dijk
 
Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Fabien Potencier
 
Marc’s (bio)perl course
Marc’s (bio)perl courseMarc’s (bio)perl course
Marc’s (bio)perl courseMarc Logghe
 
jQuery - Introdução
jQuery - IntroduçãojQuery - Introdução
jQuery - IntroduçãoGustavo Dutra
 
Symfony components in the wild, PHPNW12
Symfony components in the wild, PHPNW12Symfony components in the wild, PHPNW12
Symfony components in the wild, PHPNW12Jakub Zalas
 
Keeping It Small with Slim
Keeping It Small with SlimKeeping It Small with Slim
Keeping It Small with SlimRaven Tools
 
Drupal is Stupid (But I Love It Anyway)
Drupal is Stupid (But I Love It Anyway)Drupal is Stupid (But I Love It Anyway)
Drupal is Stupid (But I Love It Anyway)brockboland
 
Dependency injection-zendcon-2010
Dependency injection-zendcon-2010Dependency injection-zendcon-2010
Dependency injection-zendcon-2010Fabien Potencier
 
PHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php frameworkPHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php frameworkG Woo
 

What's hot (18)

The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of Lithium
 
Php Using Arrays
Php Using ArraysPhp Using Arrays
Php Using Arrays
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
 
Laravel collections an overview - Laravel SP
Laravel collections an overview - Laravel SPLaravel collections an overview - Laravel SP
Laravel collections an overview - Laravel SP
 
Php array
Php arrayPhp array
Php array
 
Php array
Php arrayPhp array
Php array
 
Arrays in PHP
Arrays in PHPArrays in PHP
Arrays in PHP
 
Refactoring using Codeception
Refactoring using CodeceptionRefactoring using Codeception
Refactoring using Codeception
 
Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)
 
Marc’s (bio)perl course
Marc’s (bio)perl courseMarc’s (bio)perl course
Marc’s (bio)perl course
 
jQuery - Introdução
jQuery - IntroduçãojQuery - Introdução
jQuery - Introdução
 
Symfony components in the wild, PHPNW12
Symfony components in the wild, PHPNW12Symfony components in the wild, PHPNW12
Symfony components in the wild, PHPNW12
 
Keeping It Small with Slim
Keeping It Small with SlimKeeping It Small with Slim
Keeping It Small with Slim
 
Lithium Best
Lithium Best Lithium Best
Lithium Best
 
Dades i operadors
Dades i operadorsDades i operadors
Dades i operadors
 
Drupal is Stupid (But I Love It Anyway)
Drupal is Stupid (But I Love It Anyway)Drupal is Stupid (But I Love It Anyway)
Drupal is Stupid (But I Love It Anyway)
 
Dependency injection-zendcon-2010
Dependency injection-zendcon-2010Dependency injection-zendcon-2010
Dependency injection-zendcon-2010
 
PHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php frameworkPHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php framework
 

Similar to PHP Collections: Build Strongly Typed, Portable and Testable Collections

Working with Groovy Collections
Working with Groovy CollectionsWorking with Groovy Collections
Working with Groovy CollectionsTed Vinke
 
DBIx::Class introduction - 2010
DBIx::Class introduction - 2010DBIx::Class introduction - 2010
DBIx::Class introduction - 2010leo lapworth
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Developmentjsmith92
 
Practical PHP 5.3
Practical PHP 5.3Practical PHP 5.3
Practical PHP 5.3Nate Abele
 
Drools5 Community Training Module 3 Drools Expert DRL Syntax
Drools5 Community Training Module 3 Drools Expert DRL SyntaxDrools5 Community Training Module 3 Drools Expert DRL Syntax
Drools5 Community Training Module 3 Drools Expert DRL SyntaxMauricio (Salaboy) Salatino
 
BASH Variables Part 1: Basic Interpolation
BASH Variables Part 1: Basic InterpolationBASH Variables Part 1: Basic Interpolation
BASH Variables Part 1: Basic InterpolationWorkhorse Computing
 

Similar to PHP Collections: Build Strongly Typed, Portable and Testable Collections (10)

Dando nome aos códigos
Dando nome aos códigosDando nome aos códigos
Dando nome aos códigos
 
Working with Groovy Collections
Working with Groovy CollectionsWorking with Groovy Collections
Working with Groovy Collections
 
DBIx::Class introduction - 2010
DBIx::Class introduction - 2010DBIx::Class introduction - 2010
DBIx::Class introduction - 2010
 
Arrays in php
Arrays in phpArrays in php
Arrays in php
 
Xpath & xquery
Xpath & xqueryXpath & xquery
Xpath & xquery
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
 
groovy & grails - lecture 2
groovy & grails - lecture 2groovy & grails - lecture 2
groovy & grails - lecture 2
 
Practical PHP 5.3
Practical PHP 5.3Practical PHP 5.3
Practical PHP 5.3
 
Drools5 Community Training Module 3 Drools Expert DRL Syntax
Drools5 Community Training Module 3 Drools Expert DRL SyntaxDrools5 Community Training Module 3 Drools Expert DRL Syntax
Drools5 Community Training Module 3 Drools Expert DRL Syntax
 
BASH Variables Part 1: Basic Interpolation
BASH Variables Part 1: Basic InterpolationBASH Variables Part 1: Basic Interpolation
BASH Variables Part 1: Basic Interpolation
 

Recently uploaded

Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
[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
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
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
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 

Recently uploaded (20)

Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
[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
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
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...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
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...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 

PHP Collections: Build Strongly Typed, Portable and Testable Collections

  • 1. May the 4th PHP CollectionsImage by statefarm
  • 2. • Object Relationships… • Perfect for One-To-Many Joins… • Traditionally just arrays which were good… WHY?
  • 3. • No rules about what is stored in the array… • No rules about how to store/retrieve… • Often public… • No separation of concerns… • Arrays are by default passed byValue… • Array[‘Notation’]… WHATS WRONG WITH ARRAYS?
  • 4. • Easy to use… • Easy to add, access, remove items… • Easy to traverse/loop… • How many array_ functions are there?… WHAT WAS RIGHT WITH ARRAYS?
  • 5. • It’s a “bucket” of objects • So, essentially, it’s a wrapper for an array… • But encapsulated with rules… • We can control the indexes… • We know more about the content types… • It can have non-member properties WHAT IS A COLLECTION CLASS?
  • 6. • private $items = array(); // property… • traversable… • countable… • Other Interfaces?
 e.g. JsonSerializable() or toJSON() ATTRIBUTES OF A COLLECTION CLASS
  • 7. • Arrays are mutable… • Collection Classes are often mutable… • mutability is a choice to be made early on… • The Immutable class is lightweight… MUTABILITY
  • 8. • with function addItem(FixedType $item){}… • we now have type checking • adding individual elements MUTABILITY &TYPE CHECKING
  • 9. • Only one way an object can be immutable…
 • __construct($items){
 $this->items = $items
 } • It is fixed after instantiation, no setItems / addItems methods… IMMUTABILITY &TYPE CHECKING
  • 11. // the old way
 Class Artist {
 
 public $albums = array();
 
 private $name;
 
 public function __construct($name) {
 $this->name = $name;
 }
 
 }
 
 $artist = new Artist('Prince');
 $artist->albums[] = '1999';
 $artist->albums[] = 'Purple Rain';

  • 12. Class Artist {
 
 private $albums = array();
 
 private $name;
 
 public function __construct($name) {
 $this->name = $name;
 }
 
 public function addItem($item) {
 $this->albums[] = $item;
 }
 
 }
 
 $artist = new Artist('Prince');
 $artist->addItem[] = 'Purple Rain';
  • 13. Class Artist {
 
 /**
 * @var AlbumCollection
 */
 private $albums;
 
 
 public function setAlbums($albums)
 {
 $this->albums = $albums;
 }
 
 //...
 }
 
 
 Class AlbumCollection {
 
 private $items = array();
 
 public function addItem(Album $album) {
 $this->items[] = $album;
 }
 
 }
  • 14. // Using the Collection Class 
 $artist = new Artist('Prince');
 
 // Build The Album Collection
 $albums = new AlbumCollection(); // Note we add Album types
 $albums->addItem( new Album('1999') );
 $albums->addItem( new Album(‘Purple Rain') );
 $albums->addItem( new Album(‘Sign O The Times') );
 
 // Set the Collection as an Artist property
 $artist->setAlbums($albums);
  • 16. Class AlbumCollection implements IteratorAggregate , Countable {
 
 private $items = array();
 
 public function addItem(Album $album) {
 $this->items[] = $album;
 }
 
 // Implement Traversable (Iterator Aggregate) 
 // Interface
 public function getIterator() {
 return new ArrayIterator($this->items);
 }
 
 // Implement Countable Interface
 public function count() {
 return count($this->items);
 }
 
 }
  • 17. • Our app will contain more than one collection… • Remember DRY principles… • Don’t copy/paste the interface implementations… ABSTRACT FOR PORTABLITY
  • 18. abstract Class BaseCollection implements Countable, IteratorAggregate 
 {
 private $items = array();
 
 // Implement Traversable via // IteratorAggregate Interface
 public function getIterator() {
 return new ArrayIterator($this->items);
 }
 
 // Implement Countable Interface
 public function count() {
 return count($this->items);
 }
 
 }

  • 19. // An Artist has many Albums
 Class AlbumCollection extends BaseCollection {
 
 private $items = array();
 
 public function addItem(Album $album) {
 $this->items[] = $album;
 }
 
 }
 
 // Albums have many Songs
 Class SongCollection extends BaseCollection {
 
 private $items = array();
 
 public function addItem(Song $song) {
 $this->items[] = $song;
 }
 
 }
  • 20. class Artist {
 
 // @var AlbumCollection
 protected $albums;
 
 // @var SongCollection
 protected $songs;
 
 // @var TourCollection
 protected $concerts;
 
 // MetadataCollection
 protected $metadata;
 
 // GenreCollection;
 protected $genres;
 
 // Tags Collection
 protected $tags;
 
 }
  • 22.
  • 23. • Pass an indeterminate number of parameters… • Can pack a list of arguments… • Can unpack an array to a list of arguments… • Can be used in the function call or definition… • So… PHP5.6+ HASTHE …TOKEN
 THEVARIABLE LENGTHTOKEN bit.ly/VarL3nT0k
  • 24. WITH IT WE CAN CREATE
 STRONGLY TYPED ARRAYS
  • 25. 
 Class AlbumCollection extends BaseCollection {
 
 private $items = array(); // Strongly typed, unknown length // All items passed must be of type Album public function __construct(Album ...$albums)
 {
 $this->items = $albums;
 }
 
 }
 
 $batman = new Album('Batman');
 $purple = new Album('Purple Rain’); // this works, but it’s messy
 $albums = new AlbumCollection($batman, $purple);

  • 26. 
 Class AlbumCollection extends BaseCollection {
 
 //…
 
 }
 // we can create an array of Albums
 // or foreach through a DB powered list $Albums[] = new Album('Batman');
 $Albums[] = new Album('Purple Rain’); $Albums[] = new Album('Dirty Mind');
 $Albums[] = new Album('Diamonds and Pearls');
 // this wont work
 $collection = new AlbumCollection($Albums);
 // this WILL work, using ‘…’ to unpack the Array
 $collection = new AlbumCollection(…$Albums);

  • 27. • We are now portable thanks to our abstract collection • We are strongly typed • We are decoupled, each type and collection can be independently tested PORTABLE &TESTABLE
  • 28. • IteratorAggregate Interface as a minimum • extend ArrayObject
 implements IteratorAggregate,ArrayAccess, Serializable, Countable • Only implement the functionality that you 
 will use/need USETHE SPL…
  • 29. • Add commonly used functionlaity to your base class • e.g. findBy($property, $value)
 BUILD ONYOUR BASE public function findBy($property, $value)
 {
 // look for an accessor method e.g. getTitle() $method = “get" . ucwords($property); foreach ($this->items as $key => $obj) { if (method_exists($obj, $method) { if ($obj->{$method}() == $property) { return($obj); } } } 
 }
  • 30. BUILD ONYOUR CONCRETE CLASS 
 Class SongCollection extends BaseCollection {
 
 protected $items;
 
 // each song has a duration, 
 // collection has a total duration
 private $totalDuration;
 
 public function getTotalDuration()
 {
 $totalDuration= 0;
 foreach($this->items as $song) {
 $totalDuration += $song->duration;
 }
 }
 
 }
  • 31. • Many Frameworks, especially ORM components have their own Collection implementations • If you use a Framework investigate the options
 Doctrine ArrayCollection, IlluminateSupportCollection • If you aren’t using a framework…
 …Learn from the Frameworks A FINAL WORD ON FRAMEWORKS
  • 32. T H A N K Y O U