I n t r odu ct ion t o
Obj e ct - or ie n t e d
pr ogr a m m in g w it h PH P
Marcus Börger
Overview
; What is OOP?
; PHP and OOP
; Except ions
; I t erat ors
; Reflect ion
What is OOP
c l as s Us el es s ex t ends Nons ens e
{
abs t r ac t f unc t i on bl aBl a( ) ;
What does OOP aim t o
achieve?
; Allow com part m ent alized refact oring of code.
; Prom ot e code re- use.
; Prom ot e ext ensibilit y, flexibilit y and adapt abilit y.
; Bet t er for t eam developm ent .
; Many pat t erns are designed for OOP.
; Som e pat t erns lead t o m uch m ore efficient code.
; Do you need t o use OOP t o achieve t hese goals?
; Of course not .
What are t he feat ures of
OOP?
; Encapsulat ion
; I nherit ance
Encapsulat ion
; Encapsulat ion is about grouping of funct ionalit y
Encapsulat ion
; Encapsulat ion is about grouping of funct ionalit y
( operat ions) and relat ed dat a ( at t ribut es) t oget her int o a coherent dat a st ruct ure ( classes) .
; Classes represent com plex dat a t ypes and t he
Encapsulat ion
; Encapsulat ion is about grouping of funct ionalit y
( operat ions) and relat ed dat a ( at t ribut es) t oget her int o a coherent dat a st ruct ure ( classes) .
; Classes represent com plex dat a t ypes and t he
operat ions t hat act on t hem . An obj ect is a part icular inst ance of a class.
; The basic idea is t o re- code real life.
Encapsulat ion
; Encapsulat ion is about grouping of funct ionalit y
( operat ions) and relat ed dat a ( at t ribut es) t oget her int o a coherent dat a st ruct ure ( classes) .
; Classes represent com plex dat a t ypes and t he
operat ions t hat act on t hem . An obj ect is a part icular inst ance of a class.
; The basic idea is t o re- code real life.
Encapsulat ion: Are Obj ect s
Just Dict ionaries?
; I n PHP 4 obj ect s were lit t le m ore t han arrays.
; I n PHP 5 you get m uch m ore cont rol by visibilit y,
int erfaces, t ype hint s, int ercept ors and m ore.
; Anot her difference is coherency. Classes can be
t old t o aut om at ically execut e specific code on obj ect creat ion and dest ruct ion.
c l as s Si mpl e {
Dat a Hiding
; Anot her difference bet ween obj ect s and arrays is
t hat obj ect s perm it st rict visibilit y sem ant ics. Dat a hiding eases refact oring by cont rolling what ot her part ies can access in your code.
; public anyone can access it
; prot ect ed only descendant s can access it
; privat e only you can access it
; final no one can re- declare it
; abst ract som eone else will im plem ent t his
Why have t hese in PHP?
I nherit ance
; I nherit ance allows a class t o specialize ( or ext end)
anot her class and inherit all it s m et hods, propert ies and behaviors.
; This prom ot es
; Ext ensibilit y ; Reusabilit y
; Code Consolidat ion ; Abst ract ion
The Problem of Code
Duplicat ion
; Code duplicat ion cont radict s m aint ainabilit y.
You oft en end up wit h code t hat looks like t his:
f unc t i on f oo_t o_x ml ( $f oo) {
/ / gener i c s t uf f
/ / f oo- s pec i f i c s t uf f
}
f unc t i on bar _t o_x ml ( $bar ) {
/ / gener i c s t uf f
/ / bar s pec i f i c s t uf f
The Problem of Code
Duplicat ion
; You could clean t hat up as follows
f unc t i on bas e_t o_x ml ( $dat a) { / * . . . * / } f unc t i on f oo_t o_x ml ( $f oo) {
bas e_t o_x ml ( $f oo) ;
/ / f oo s pec i f i c s t uf f
}
f unc t i on bar _t o_x ml ( $bar ) {
bas e_t o_x ml ( $bar ) ;
/ / bar s pec i f i c s t uf f
}
; But it ’s hard t o keep base_t o_xm l( ) working for
The Problem of Code
Duplicat ion
; I n an OOP st yle you would creat e classes for t he
Foo and Bar classes t hat ext end from a base class t hat handles com m on funct ionalit y.
; Sharing a base class prom ot es sam eness.
Polym orphism ?
; Suppose a calendar t hat is a collect ion of ent ries.
Procedurally dislpaying all t he ent ries m ight look like:
f or eac h( $ent r i es as $ent r y) { s wi t c h( $ent r y[ ’ t y pe’ ] ) { c as e ' pr of es s i onal ' :
di s pl ay _pr of es s i onal _ent r y( $ent r y) ; br eak ;
c as e ' per s onal ' :
di s pl ay _per s onal _ent r y( $ent r y) ; br eak ;
Sim plicit y t hrough
Polym orphism
; I n t he OOP paradigm t his would look like:
f or eac h( $ent r i es as $ent r y) {
$ent r y- >di s pl ay( ) ; }
; The key point is we don't have t o m odify t his loop
t o add new t ypes. When we add a new t ype, t hat t ype get s a display( ) m et hod so t hat it knows how t o display it self, and we’re done.
; Also t his is m uch fast er because we do not have t o
Sim plicit y t hrough Magic?
; Act ually in PHP you m ight want t his:
f or eac h( $ent r i es as $ent r y) { ec ho $ent r y;
}
; A class can have a __t oSt r i ng( ) m et hod which
defines how it s obj ect s are convert ed int o a t ext ual represent at ion.
Polym orphism
t he ot her way round
; Unlike ot her languages PHP does not and will not
offer polym orphism for m et hod calling. Thus t he following will never be available in PHP
< ?php
class Test {
funct ion t oXML(Personal $obj) / / …
funct ion t oXML(Professional $obj) / / …
} ?>
; To work around t his
; Use t he ot her way round ( call ot her m et hods from a single t oXML( ) funct ion in a polym orphic way)
Anot her exam ple
c l as s Humans {
publ i c f unc t i on __c ons t r uc t ( $name) {
/ * . . . * /
}
Som e I nherit ance
c l as s Humans {
publ i c f unc t i on __c ons t r uc t ( $name) { / * . . . * / } publ i c f unc t i on eat ( ) { / * . . . * / }
publ i c f unc t i on s l eep( ) { / * . . . * / } publ i c f unc t i on s nor e( ) { / * . . . * / } publ i c f unc t i on wak eup( ) { / * . . . * / } }
c l as s Women ex t ends Humans {
I nherit ance+ Polym orphism
c l as s Humans {
publ i c f unc t i on __c ons t r uc t ( $name) { / * . . . * / } publ i c f unc t i on eat ( ) { / * . . . * / }
publ i c f unc t i on s l eep( ) { / * . . . * / } publ i c f unc t i on wak eup( ) { / * . . . * / } }
c l as s Women ex t ends Humans {
publ i c f unc t i on gi v eBi r t h( ) { / * . . . * / } }
c l as s Men ex t ends Humans {
A lit t le abst ract ion
abs t r ac t c l as s Humans {
publ i c f unc t i on __c ons t r uc t ( $name) { / * . . . * / }
abs t r ac t publ i c f unc t i on gender ( ) ; publ i c f unc t i on eat ( ) { / * . . . * / } publ i c f unc t i on s l eep( ) { / * . . . * / } publ i c f unc t i on wak eup( ) { / * . . . * / } }
c l as s Women ex t ends Humans {
publ i c f unc t i on gender ( ) { r et ur n ' f emal e' ; } publ i c f unc t i on gi v eBi r t h( ) { / * . . . * / }
}
c l as s Men ex t ends Humans {
publ i c f unc t i on gender ( ) { r et ur n ' mal e' ; } publ i c f unc t i on s nor e( ) { / * . . . * / }
A lit t le abst ract ion
abs t r ac t c l as s Humans {
publ i c f unc t i on __c ons t r uc t ( $name) { / * . . . * / } abs t r ac t publ i c f unc t i on gender ( ) ;
publ i c f unc t i on eat ( ) { / * . . . * / } publ i c f unc t i on s l eep( ) { / * . . . * / } publ i c f unc t i on wak eup( ) { / * . . . * / } }
c l as s Women ex t ends Humans {
f i nal publ i c f unc t i on gender ( ) { r et ur n ' f ' ; } publ i c f unc t i on gi v eBi r t h( ) { / * . . . * / }
}
c l as s Men ex t ends Humans {
f i nal publ i c f unc t i on gender ( ) { r et ur n ' m' ; } publ i c f unc t i on s nor e( ) { / * . . . * / }
PHP 4 and OOP ?
Poor Obj ect m odel
; Met hods
: No visibilit y
: No abst ract s, no final
: St at ic wit hout declarat ion
; Propert ies
: No st at ic propert ies
: No const ant s
; I nherit ance
: No abst ract , final inherit ance, no int erfaces
: No prot ot ype checking, no t ypes
; Obj ect handling : Copied by value
ZE2's revam ped obj ect m odel
; Obj ect s are referenced by ident ifiers
; Const ruct ors and Dest ruct ors
; St at ic m em bers
; Const ant s
; Visibilit y
; I nt erfaces
; Final and abst ract m em bers
; I nt ercept ors
; Except ions
; Reflect ion API
Revam ped Obj ect Model
; PHP 5 has really good OOP support
; Bet t er code reuse
; Bet t er for t eam developm ent ; Easier t o refact or
Obj ect s referenced by
ident ifiers
; Obj ect s are no longer som ewhat special arrays
; Obj ect s are no longer copied by default
; Obj ect s m ay be copied using clone/ __clone( )
c l as s Obj ec t { } ;
$obj = new Obj ec t ( ) ;
$r ef = $obj ;
$dup = c l one $obj ;
Class Object
$obj $ref $dup
Const ruct ors and Dest ruct ors
; Const ruct ors/ Dest ruct ors cont rol obj ect lifet im e
; Const ruct ors m ay have bot h new OR old st yle nam e ; New st yle const ruct ors are preferred
; Const ruct ors m ust not use inherit ed prot ocol
; Dest ruct ors are called when delet ing t he last reference ; No part icular or cont rollable order during shut down
; Dest ruct ors cannot have param et ers
; Since PHP 5.0.1 dest ruct ors can work w it h resources
c l as s Obj ec t {
f unc t i on __c ons t r uc t ( ) { } f unc t i on __des t r uc t ( ) { } }
$obj = new Obj ec t ( ) ;
Const ruct ors and Dest ruct ors
; Parent s m ust be called m anually
c l as s Bas e {
f unc t i on __c ons t r uc t ( ) { } f unc t i on __des t r uc t ( ) { } }
c l as s Obj ec t ex t ends Bas e { f unc t i on __c ons t r uc t ( ) {
par ent : : __c ons t r uc t ( ) ; }
f unc t i on __des t r uc t ( ) {
par ent : : __des t r uc t ( ) ; }
}
$obj = new Obj ec t ( ) ;
Default propert y values
; Propert ies can have default values
; Bound t o t he class not t o t he obj ect
; Default values cannot be changed but overw rit t en
St at ic m em bers
; St at ic m et hods and propert ies
; Bound t o t he class not t o t he obj ect
; Only exist s once per class rat her t han per inst ance
Pseudo const ant s
; __CLASS__ shows t he current class nam e
; __METHOD__ shows class and m et hod or funct ion
; s el f references t he class it self
; par ent references t he parent class
Visibilit y
; Cont rolling m em ber visibilit y / I nform at ion hiding
Const ruct or visibilit y
; A prot ect ed const ruct or prevent s inst ant iat ion
c l as s Bas e {
pr ot ec t ed f unc t i on __c ons t r uc t ( ) { }
}
c l as s Der i v ed ex t ends Bas e {
/ / c ons t r uc t or i s s t i l l pr ot ec t ed
s t at i c f unc t i on get Bas e( ) {
r et ur n new Bas e; / / Fac t or y pat t er n
} }
c l as s Thr ee ex t ends Der i v ed {
publ i c f unc t i on __c ons t r uc t ( ) { }
The Singlet on pat t ern
; Som et im es you want only a single inst ance of
aclass t o ever exist .
; DB connect ions
; An obj ect represent ing t he user or connect ion.
Const ant s
; Const ant s are read only st at ic propert ies
; Const ant s are always public
c l as s Bas e {
c ons t gr eet i ng = " Hel l o\ n" ; }
c l as s Der v i ed ex t ends Bas e {
c ons t gr eet i ng = " Hel l o Wor l d\ n" ; s t at i c f unc t i on f unc( ) {
ec ho par ent : : gr eet i ng; }
}
ec ho Bas e: : gr eet i ng; ec ho Der i v ed: : gr eet i ng;
Abst ract m em bers
; Met hods can be abst ract
; They don’t have a body
; A class wit h an abst ract m et hod m ust be abst ract
; Classes can be m ade abst ract
; The class cannot be inst ant iat ed
; Propert ies cannot be m ade abst ract
abs t r ac t c l as s Bas e {
abs t r ac t f unc t i on no_body( ) ; }
c l as s Der i v ed ex t ends Bas e {
Final m em bers
; Met hods can be final
; They cannot be overwrit t en ; They are class invariant s
; Classes can be final
; They cannot be inherit ed
c l as s Bas e {
f i nal f unc t i on i nv ar i ant ( ) { ec ho " Hel l o\ n" ; } }
c l as s Der i v ed ex t ends Bas e { }
I nt erfaces
; I nt erfaces describe an abst ract class prot ocol
Propert y kinds
; Declared propert ies
; May have a default value ; Can have select ed visibilit y
; I m plicit public propert ies
; Declared by sim ply using t hem in ANY m et hod
; Virt ual propert ies
; Handled by int ercept or m et hods
; St at ic propert ies
Obj ect t o St ring conversion
; __t oSt ring( ) : sem i- aut om at ic obj ect t o st ringconversion wit h echo and print ( aut om at ic st art ing wit h 5.2)
c l as s Obj ec t {
f unc t i on __t oSt r i ng( ) {
r et ur n ' Obj ec t as s t r i ng' ; }
}
$o = new Obj ec t ;
ec ho $o; / / does c al l __t oSt r i ng
I nt ercept ors
; Allow t o dynam ically handle non class m em bers
; Lazy init ializat ion of propert ies
; Sim ulat ing Obj ect aggregat ion and Mult iple inherit ance
Typehint ing
; PHP 5 allows t o easily force a t ype of a param et er
; PHP does not allow NULL for t ypehint s
; Typehint s m ust be inherit ed as given in base class ; PHP 5.1 offers t ypehint ing wit h arrays
; PHP 5.2 offers opt ional t ypehint ed param et ers ( = NULL) c l as s Obj ec t {
publ i c f unc t i on c ompar e( Obj ec t $ot her ) {
/ / Some c ode her e
}
publ i c f unc t i on c ompar e2( $ot her ) {
i f ( i s _nul l ( $ot her ) | | $ot her i ns t anc eof Obj ec t ) {
/ / Some c ode her e
Class Design
; I t is im port ant t o t hink about your class hierarchy
; Avoid very deep or broad inherit ance graphs
; PHP only support s is- a and has- a relat ions
Vehicle
Truck
Car Bus Diesel Gasoline
Engine
Too St rict or t oo Weak?
; PHP t ries t o prevent you from doing som e errors
; You are bound t o keep inherit ed signat ures ; You cannot change from ref t o non- ref ret urn
; Yet PHP allows absolut e flexibilit y
; Just do not define a signat ure
Dynam ic class loading
; __aut ol oad( ) is good
; Requires a single file for each class ; Only load class files when necessary
; No need t o parse/ com pile unneeded classes
; No need t o check which class files t o load
: Addit ional user space code
1 Only one single loader m odel is possible
__aut ol oad & r equi r e_onc e
; St or e t he c l as s l oader i n an i nc l ude f i l e
; I n eac h s c r i pt :
r equi r e_onc e( ' <pat h>/ aut ol oad. i nc ' ) ; Us e I NI opt i on:
aut o_pr epend_f i l e=<pat h>/ aut ol oad. i nc
<?php
f unc t i on __aut ol oad( $c l as s _name) {
r equi r e_onc e(
di r name( __FI LE__) . ' / ' . $c l as s _name . ' . p5c ' ) ; }
SPL's class loading
; Support s fast default im plem ent at ion
; Look int o pat h's specified by I NI opt ion include_pat h ; Look for specified file ext ensions ( .inc, .php)
; Abilit y t o regist er m ult iple user defined loaders
; Overwrit es ZEND engine's __aut oload( ) cache
; You need t o regist er __aut oload if using spl's aut oload
<?php
s pl _aut ol oad_r egi s t er ( ' s pl _aut ol oad' ) ; i f ( f unc t i on_ex i s t s( ' __aut ol oad' ) ) {
s pl _aut ol oad_r egi s t er ( ' __aut ol oad' ) ; }
SPL's class loading
; s pl _aut ol oad( $c l as s _name, $ex t ens i ons=NULL)
Load a class from a file in include pat h Fast c code im plem ent at ion
; s pl _aut ol oad_ex t ens i ons( $ex t ens i ons=NULL)
Get or set filenam e ext ensions
; s pl _aut ol oad_r egi s t er ( $l oader _f unc t i on)
Regist er a single loader funct ion
; s pl _aut ol oad_unr egi s t er ( $l oader _f unc t i on)
Unregist er a single loader funct ion
; s pl _aut ol oad_f unc t i ons( )
List all regist ered loader funct ions
Except ions
; Respect t hese rules
1. Except ions are except ions
2. Never use except ions for cont rol flow
3. Never ever use except ions for param et er passing
<?php
t r y {
/ / y our c ode
t hr ow new Ex c ept i on( ) ; }
c at c h ( Ex c ept i on $e) {
/ / ex c ept i on handl i ng
}
Except ion specializat ion
; Except ions should be specialized
; Except ions should inherit built in class except ion
c l as s Your Ex c ept i on ex t ends Ex c ept i on { }
t r y {
/ / y our c ode
t hr ow new Your Ex c ept i on( ) ; }
c at c h ( Your Ex c ept i on $e) {
/ / ex c ept i on handl i ng
}
c at c h ( Ex c ept i on $e) {
/ / ex c ept i on handl i ng
Except ion specializat ion
; Except ion blocks can be nest ed
Pract ical use of except ions
; Const ruct or failure
; Convert ing errors/ warnings t o except ions
; Sim plify error handling
Const ruct or failure
; I n PHP 4.4 you would sim ply uns et ( $t hi s)
; Provide an argum ent t o receive t he error condit ion
<?php
c l as s Obj ec t
{
f unc t i on __c ons t r uc t ( & $f ai l ur e) / / " Obj ec t " i n PHP 4
{
$f ai l ur e = t r ue; }
}
$er r or = f al s e;
$o = new Obj ec t ( $er r or ) ; i f ( ! $er r or ) {
/ / er r or handl i ng, NOTE: t he obj ec t was c ons t r uc t ed
Const ruct or failure
; I n 5 const ruct ors do not ret urn t he creat ed obj ect
; Except ions allow t o handle failed const ruct ors
Convert Errors t o Except ions
; I m plem ent ing PHP 5.1 class ErrorExcept ion
Convert Errors t o Except ions
; I m plem ent ing t he error handler
<?php
f unc t i on Er r or s ToEx c ept i ons( $er r no, $ms g, $f i l e, $l i ne) {
t hr ow new Er r or Ex c ept i on( $ms g, 0, $er r no, $f i l e, $l i ne) ; }
s et _er r or _handl er ( ' Er r or s ToEx c ept i ons ' ) ;
Sim plify error handling
; Typical dat abase access code cont ains lot s of if's
Sim plify error handling
PDO: : ERRMODE_EXCEPTI ON) ;
SPL Except ions
; SPL provides a st andard set of except ions
General dist inguishing
; Logi c Ex c ept i onÎAnyt hing t hat could have been det ect ed at
com pile t im e, during applicat ion design or by t he good old t echnology:
" look closely"
; Runt i meEx c ept i on
ÎAnyt hing t hat is unexpect ed during runt im e
LogicExcept ion
; Funct ion not found or sim ilar
BadMet hodCal l Ex c ept i on
; Value not in allowed dom ain
; Argum ent not valid
; Lengt h exceeded
RunTim eExcept ion
; An act ual value is out of bounds
; Buffer or ot her overflow sit uat ion
; Value out side expect ed range
; Buffer or ot her underflow sit uat ion
Overloading __call
; I f using __call, ensure only valid calls are m ade
I nt erfaces and __call
; I nt erface funct ions cannot be handled by __call
I nt erfaces and __call
; I nt erface funct ions cannot be handled by __call
; ...or provide t he funct ions ( here as proxy/ forward)
Expect ing form at t ed dat a
; Opening a file for reading
$f o = new Spl Fi l eObj ec t ( $f i l e) ;
$f o- >s et Fl ags( Spl Fi l eObj ec t : : DROP_NEWLI NE) ;
$dat a = ar r ay( ) ;
Run-Time:
Expect ing form at t ed dat a
; Cehcking dat a aft er pre- processing
Expect ing form at t ed dat a
; Processing pre- checked dat a
Reflect ion API
; Can reflect nearly all aspect s of your PHP code
; Funct ions
; Classes, Met hods, Propert ies ; Ext ensions
c l as s Foo {
publ i c $pr op;
f unc t i on Func( $name) { ec ho " Hel l o $name" ; }
}
Ref l ec t i onCl as s: : ex por t ( ' Foo' ) ;
Ref l ec t i onObj ec t : : ex por t ( new Foo) ;
Ref l ec t i onMet hod: : ex por t ( ' Foo' , ' f unc ' ) ;
Ref l ec t i onPr oper t y: : ex por t ( ' Foo' , ' pr op' ) ;
Dynam ic obj ect creat ion
; Reflect ion allows dynam ic obj ect creat ion
c l as s Tes t {
f unc t i on __c ons t r uc t ( $x, $y = NULL) {
$t hi s- >x = $x;
$t hi s- >y = $y; }
}
f unc t i on new_obj ec t _ar r ay( $c l s, $ar gs = NULL) { r et ur n c al l _us er _f unc _ar r ay(
ar r ay ( new Ref l ec t i onCl as s( $c l s) , ' newI ns t anc e' ) ,
$ar gs) ; }
new_obj ec t _ar r ay( ' s t dCl as s ' ) ;
new_obj ec t _ar r ay( ' Tes t ' , ar r ay ( 1) ) ;
Built - in I nt erfaces
; PHP 5 cont ains built - in int erfaces t hat allow you t o
change t he way t he engine t reat s obj ect s.
; Ar r ay Ac c es s ; I t er at or
; I t er at or Aggr egat e
; Built - in ext ension SPL provides m ore I nt erfaces
and Classes
; Ar r ay Obj ec t , Ar r ay I t er at or ; Fi l t er I t er at or
; Rec ur s i v eI t er at or
; Use CLI :
php - - r e SPL
ArrayAccess
; Allows for creat ing obj ect s t hat can be
t ransparent ly accessed by array synt ax.
; When com bined wit h t he it erat or int erface, it
allows for creat ing ‘arrays wit h special propert ies’.
i nt er f ac e Ar r ay Ac c es s {
/ / @r et ur n whet her $of f s et i s v al i d ( t r ue/ f al s e)
f unc t i on of f s et Ex i s t s( $of f s et ) ;
/ / @r et ur n t he v al ue as s oc i at ed wi t h $of f s et
f unc t i on of f s et Get ( $of f s et ) ;
/ / as s oc i at e $v al ue wi t h $of f s et ( s t or e t he dat a)
f unc t i on of f s et Set ( $of f s et , $v al ue) ;
/ / uns et t he dat a as s oc i at ed wi t h $of f s et
ArrayAccess
; ArrayAccess does not allow references
( t he following is an error)
c l as s My Ar r ay ex t ends Ar r ay Ac c es s {
f unc t i on &of f s et Get ( $of f s et ) { / * . . . * / }
f unc t i on of f s et Set ( $of f s et , &$v al ue) { / * . . . * / } f unc t i on of f s et Ex i s t s( $of f s et ) { / * . . . * / }
ArrayAccess Exam ple
; We want t o creat e variables which can be shared
bet ween processes.
; We will set up int ercept ion so t hat access at t em pt s
A Trivial Exam ple
<?php
i f ( ! c l as s _ex i s t s( ' DbaReader ' , f al s e) ) {
r equi r e_onc e ‘ dbadeader . i nc ’ ; }
$_SHARED = new DbaReader ( ' / t mp/ . c ount er ' , ' f l at f i l e' ) ;
$_SHARED[ ' c ount er ' ] += 1;
pr i nt f ( " PI D: %d\ nCOUNTER: %d\ n" , get my pi d( ) ,
$_SHARED[ ' c ount er ' ] ) ;
I t erat ors
; Norm al obj ect s behave like arrays when used wit h
t he foreach const ruct
; Specialized I t erat or obj ect s can be it erat ed
different ly
<?php
c l as s Obj ec t {
publ i c $pr op1 = " Hel l o " ; publ i c $pr op2 = " Wor l d\ n" ; }
f or eac h( new Obj ec t as $pr op) { ec ho $pr op;
}
What are I t erat ors
; I t erat ors are a concept t o it erat e anyt hing t hat
cont ains ot her t hings.
What are I t erat ors
; I t erat ors are a concept t o it erat e anyt hing t hat
cont ains ot her t hings. Exam ples:
; Values and Keys in an array Ar r ay Obj ec t , Ar r ay I t er at or
; Text lines in a file Spl Fi l eObj ec t
; Files in a direct ory [Rec ur s i v e]Di r ec t or y I t er at or
; XML Elem ent s or At t ribut es ext : Sim pleXML, DOM
; Dat abase query result s ext : PDO, SQLit e, MySQLi
; Dat es in a calendar range PECL/ dat e ( ?) ; Bit s in an im age ?
What are I t erat ors
; I t erat ors are a concept t o it erat e anyt hing t hat cont ains ot her t hings. Exam ples:
; Values and Keys in an array Ar r ay Obj ec t , Ar r ay I t er at or ; Text lines in a file Spl Fi l eObj ec t
; Files in a direct ory [ Rec ur s i v e] Di r ec t or y I t er at or ; XML Elem ent s or At t ribut es ext : Sim pleXML, DOM
; Dat abase query result s ext : PDO, SQLit e, MySQLi ; Dat es in a calendar range PECL/ dat e ( ?)
; Bit s in an im age ?
; I t erat ors allow t o encapsulat e algorit hm s
; Classes and I nt erfaces provided by SPL:
Array vs. I t erat or
; An array in PHP $ar = ar r ay( )
; can be rewound: r es et ( $ar )
; is valid unless it 's key is NULL: ! i s _nul l ( k ey( $ar ) )
; have current values: c ur r ent ( $ar )
; have keys: k ey( $ar )
; can be forwarded: nex t ( $ar )
; Som et hing t hat is t raversable $i t = new I t er at or ;
; m a y know how t o be rewound: $i t - >r ewi nd( ) ( does not r et ur n t he el ement )
; should know if t here is a value: $i t - >v al i d( )
; m a y have a current value: $i t - >c ur r ent ( )
; m a y have a key: $i t - >k ey( ) ( may r et ur n NULL at any t i me)
The big difference
; Ar r a ys; require m em ory for all elem ent s ; allow t o access any elem ent direct ly
; I t e r a t or s
; only know one elem ent at a t im e
; only require m em ory for t he current elem ent ; forward access only
; Access done by m et hod calls
; Con t a in e r s
The basic concept s
; I t erat ors can be int ernal or ext ernal
also referred t o as act ive or passive
; An int ernal it erat or m odifies t he obj ect it self
; An ext ernal it erat or point s t o anot her obj ect
wit hout m odifying it
; PHP always uses ext ernal it erat ors at engine- level
I m plem ent ing I t erat ors
+ <<Implement>> getIterator () : Iterator
; Why not j ust use arrays:
f or eac h( $s ome_ar r ay as $i t em) { / * . . . * / }
; Aren't we m aking life m ore difficult t han need be?
; No! For sim ple aggregat ions t he above works fine
( t hough it ’s slow) , but not everyt hing is an array.
What about :
; Buffered result set s ; Lazy I nit ializat ion ; Direct ories
; Anyt hing not already an array
I t erat ors by exam ple
; Using I t erat ors you can efficient ly grab all groups
from I NI files
; The building blocks:
; A class t hat handles I NI files ; An abst ract filt er I t erat or
; A filt er t hat filt ers group nam es from t he I NI file input ; An I t erat or t o read all ent ries in t he I NI file
Conclusion so far
; I t erat ors require a new way of program m ing
; I t erat ors allow t o im plem ent algorit hm s
abst ract ed from dat a
; I t erat ors prom ot e code reuse
; Som e t hings are already in SPL
; Filt ering
Let ’s Talk About Pat t erns
; Pat t erns cat alog solut ions t o problem cat egories
; They consist of
; A nam e
; A descript ion of t heir problem
; A descript ion of t he solut ion
; Not so m uch.
Pat t erns sources out side OOP include:
; Archit ect ure ( t he originat or of t he paradigm )
; User I nt erface Design ( wizards, cookie crum bs,
t abs)
; Cooking ( braising, pickling)
Pat t erns We’ve Seen So Far
; Singlet on Pat t ern
; I t erat or Pat t ern
Aggregat or Pat t ern
; Pr ob le m : You have collect ions of it em s t hat you
operat e on frequent ly wit h lot s of repeat ed code.
Rem em ber our calendars:
f or eac h( $ent r i es as $ent r y) { ec ho $ent r y;
}
; Solu t ion: Creat e a cont ainer t hat im plem ent s t he
Aggregat or Pat t ern
c l as s Ent r y Aggr egat e ex t ends Ent r y {pr ot ec t ed $ent r i es; . . .
publ i c f unc t i on di s pl ay( ) {
f or eac h( $t hi s- >ent r i es as $ent r y) { $ent r y- >di s pl ay( ) ;
}
publ i c f unc t i on add( Ent r y $e) { ar r ay _pus h( $t hi s- >ent r i es, $e) ; }
}
; By ext ending Ent ry, t he aggregat e can act ually
Proxy Pat t ern
; Pr ob le m : You need t o provide access t o an
obj ect , but it has an int erface you don’t know at com pile t im e.
; Solu t ion: Use accessor/ m et hod overloading t o
dynam ically dispat ch m et hods t o t he obj ect .
; D iscu ssion: This is very t ypical of RPC- t ype
Observer Pat t ern
; Pr ob le m : You want an obj ect t o aut om at ically
not ify dependent s when it is updat ed.
; Solu t ion: Allow 'observer' t o regist er t hem selves
wit h t he observable obj ect .
; D iscu ssion: An obj ect m ay not apriori know who
m ight be int erest ed in it . The Observer pat t ern
Obj ect handling side not es
; You cannot access t he obj ect ident ifier/ handle
$obs er v er s[ ] = $obs er v er ;
; YOU need t o prevent double insert ion/ execut ion
f or eac h( $obs er v er s as $o) {
i f ( $o === $obs er v er ) r et ur n; }
$obs er v er s[ ] = $obs er v er ;
; No easy way t o delet e an obj ect from an array
f or eac h( $obs er v er s as $k => $o) { i f ( $o === $obs er v er ) {
uns et ( $obs er v er [ $k] ) ; br eak ;
Obj ect St orage in 5.2
c l as s Obj ec t St or age {
pr ot ec t ed $s t or age = ar r ay ( ) ;
f unc t i on at t ac h( $obj ) {
$t hi s- >s t or age[ s pl _obj ec t _has h( $obj ) ] = $obj ; }
f unc t i on det at c h( $obj ) {
uns et ( $t hi s- >s t or age[ s pl _obj ec t _has h( $obj ) ] ) ; }
}
c l as s My Subj ec t i mpl ement s Subj ec t {
debugging, SOAP m essage not ificat ions.
At Last som e Hint s
; List of all SPL classes PHP 5.0.0
php –r ' pr i nt _r ( ar r ay _k ey s ( s pl _c l as s es ( ) ) ) ; '
; Reflect ion of a built - in class PHP 5.1.2
php - - r c <Cl ass>
; Reflect ion of a funct ion or m et hod PHP 5.1.2
php - - r f <Funct i on>
; Reflect ion of a loaded ext ension PHP 5.1.2
php - - r e <Ext ensi on>
; Ext ension inform at ion/ configurat ion PHP 5.2.2
Reference
; Everyt hining about PHP
ht t p: / / php.net
; These slides
ht t p: / / t alks.som abo.de
; SPL Docum ent aion & Exam ples
ht t p: / / php.net / ~ helly/ php/ ext / spl
ht t p: / / cvs.php.net / php- src/ ext / spl/ exam ples ht t p: / / cvs.php.net / php- src/ ext / spl/ int ernal
; George Schlossnagle
Advanced PHP Program m ing
; Andi Gut m ans, St ig Bakken, Derick Ret hans