intermediate oop in php
TRANSCRIPT
Welcome to
php[world] 2015Wifi:SSID: Sheraton_Conferenceuser: php2015pass: sheraton
Twitter:
#phpworld Rate talks on joind.inhttps://joind.in/event/phpworld2015
Intermediate OOPin PHP
INTERMEDIATE OOP IN PHP
PHP World - November 18, 2015David Stockton
@dstockto
WHAT WE’LL COVER• Magic Methods
• Polymorphism
• Collections
• Filtering Collections
• SPL Iterator
WHAT WE’LL COVER• SPL Count
• SPL ArrayAccess
• Listener Pattern
• Loose Coupling
• High Cohesion
MAGIC METHODS
• Methods all start with __
__construct
__construct
• __construct is called when you “new” up an object
• Initialize object properties
• Don’t do work!
__destruct
• __destruct is called when an object goes out of scope
• Shut down connections, cleanup work
__call
• __call($name, array $arguments)
• Method called when method is called that is not in scope
• Method doesn’t exist
• Method is private / protected and called from outside object
__call
__callStatic
• Just like __call but for static calls out of scope
• Foo::createFromThing()
__get, __set, __isset, __unset
• In many cases, if you need one, you need them all
• Weird bugs if you don’t implement them all
__get
• __get($name)
• Called when reading an object property that’s not in scope
• $value = $foo->madeUpValue;
__get
__set
__set($name, $value)
SO, WHY DO WE NEED THEM ALL?
$foo->bar = ‘baz’;
$value = $foo->bar; // Get baz
if (isset($foo->bar)) { $value = $foo->bar; // Never get here if no __isset }
__isset__isset($name)
isset($object->variable)
__unset__unset($name)
unset($object->variable);
WHAT YOU CAN DO WITH THEM
• Implement a class that doesn’t allow dynamic values
• Implement a class that only allows values with certain naming conventions
• Automatic calling of accessors (getters and setters)
THE DOWNSIDES• Harder to follow, no “ctrl-click”
in IDEs
• No auto-complete for __call or __callStatic methods in IDEs
• Can use @method doc block to help
• @method int add() add(numeric $a, numeric $b) Add numbers
@METHOD DOCBLOCK
__SLEEP & __WAKEUP• Called on serialize() and unserialize() calls
• __sleep: Use to close connections, cleanup
• __wakeup: Use to re-establish connections, setup
• Why?
• Some things in PHP are not serializable
__toString()
• Retrieve string representation of a class
• Must return a string
• Cannot throw an exception
__toString
__toString
__cloneCreate a new object based on an existing object
Called when clone is used:
$foo = clone $bar;
__clone
• By default, clone is shallow
$foo = new Foo();
Foo$foo
Foo$bar
$foo Bar
$foo2 = clone $foo;
Foo$bar
$foo Bar
Foo$bar
$bar
CHANGING $BAR
NOW WITH __clone
$FOO = NEW FOO();
Foo$foo
Foo$bar$foo Bar
$FOO2 = CLONE $FOO;
Foo$bar$foo Bar
Foo$bar$bar
__clone called on the clone
$FOO2 = CLONE $FOO;
Foo$bar$foo Bar
Foo$bar$bar Bar
CHANGING $BAR
__invoke
• Allows an object to be used like a function or callable
• Object can be built configured and then “executed”
__invoke
__invoke
__autoload• Don’t use __autoload, use
spl_autoload_register
• Called when a class, interface, or trait is used that hasn’t been loaded
• Allows just in time loading of classes, no more requires and includes at the top of files
__set_state
• Used with var_export
• Allows setting of object variables from an array of input
__debugInfo
• New in PHP 5.6
• Controls output of var_dump
__debugInfo
var_dump
ADD __debugInfo
var_dump AGAIN
POLYMORPHISMAllow code to use different
objects in the same way
SPEAKABLEinterface
POLYMORPHISM
POLYMORPHISM
COLLECTIONS AND POLYMORPHISM
SILVERWARE DRAWER
SILVERWARECONTAINERinterface
SILVERWAREinterface
Abstract Utensil Class
“Type a quote here.”
A FORKING EXAMPLE
SILVER SPOONS
KNIFE
PUT SILVERWARE AWAY
HOW MANY UTENSILS?
• Add method getNumberOfItems
• Implement SPL Countable
SPL COUNTABLE
HOW TO USE?
RETRIEVE SPECIFIC UTENSILS
SPL TO THE RESCUE
• Implement SPL ArrayAccess
• Make our object work like an array
SPL ARRAYACCESS
SPL ARRAYACCESS
WHAT DOES THAT ALLOW?
USE AN ITERATOR:
• IMPLEMENT ITERATOR• EXTEND ONE OF THESE:
• AppendIterator• ArrayIterator• CachingIterator• CallbackFilterIterator• InfiniteIterator• …ETC.
EASY WAYExtend ArrayIterator
ADD SOME SILVERWARE
NOW WHAT? ITERATE IT!
A NEW ITERATOR
ONLY GET CLEAN UTENSILS
SPLSUBJECT / SPLOBSERVERMoving right along
IMPLEMENT SplSubject
EMAIL CLASS CONTINUED
VALIDATE USES OUR OBSERVERS
BUILD SOME OBSERVERSInvalid Emails don’t send
LIMIT SENDS BY DOMAINS?
PUT IT ALL TOGETHER
LOOSE COUPLING
LOOSE COUPLING• Minimize number of hard-coded dependencies
• Type hint interfaces, not classes
• Dependency Injection / Inversion of Control
DEPENDENCY INJECTION SIMPLY
HIGH COHESION
Do one thing well
HIGH COHESION• Do one thing well
• Methods
• Classes
• Packages / Namespaces
• Everything the class does is related to the goal
–David Stockton
“If you have to use ‘and’ to describe
what your method or class does, it’s
probably doing too much.”
PREFER COMPOSITION OVER INHERITANCE
PREFER COMPOSITION OVER INHERITANCE
• Inheritance is not the only way to expand functionality of a class
• Often it’s not even the best way
PHOTO CREDITS
• Trailer hitch - https://www.flickr.com/photos/jeremybrooks/2476396242• The Glue Side of the Force - https://www.flickr.com/photos/st3f4n/4085958000
All other photos are © David Stockton, 2015