I ntroduction to Object-oriented program m ing w ith PHP Marcus - - PowerPoint PPT Presentation

i ntroduction to object oriented program m ing w ith php
SMART_READER_LITE
LIVE PREVIEW

I ntroduction to Object-oriented program m ing w ith PHP Marcus - - PowerPoint PPT Presentation

I ntroduction to Object-oriented program m ing w ith PHP Marcus Brger PHP Quebec conference 2 0 0 7 Overview What is OOP? PHP and OOP Exceptions Iterators Reflection Patterns Marcus Brger Introduction


slide-1
SLIDE 1

I ntroduction to Object-oriented program m ing w ith PHP

Marcus Börger

PHP Quebec conference 2 0 0 7

slide-2
SLIDE 2

Marcus Börger Introduction to Object-oriented programming with PHP 2

Overview

  • What is OOP?
  • PHP and OOP
  • Exceptions
  • Iterators
  • Reflection
  • Patterns
slide-3
SLIDE 3

Marcus Börger Introduction to Object-oriented programming with PHP 3

What is OOP

cl ass Usel ess ext ends Nonsense { abst r act f unct i on bl aBl a( ) ; }

?

slide-4
SLIDE 4

Marcus Börger Introduction to Object-oriented programming with PHP 4

What does OOP aim to achieve?

  • Allow compartmentalized refactoring of code.
  • Promote code re-use.
  • Promote extensibility, flexibility and adaptability.
  • Better for team development.
  • Many patterns are designed for OOP.
  • Some patterns lead to much more efficient code.
  • Do you need to use OOP to achieve these goals?

Of course not. It’s designed to make those things easier though.

slide-5
SLIDE 5

Marcus Börger Introduction to Object-oriented programming with PHP 5

What are the features of OOP?

  • Encapsulation
  • Inheritance
  • Polymorphism
slide-6
SLIDE 6

Marcus Börger Introduction to Object-oriented programming with PHP 6

Encapsulation

  • Encapsulation is about grouping of functionality

(operations) and related data (attributes) together into a coherent data structure (classes).

slide-7
SLIDE 7

Marcus Börger Introduction to Object-oriented programming with PHP 7

Encapsulation

  • Encapsulation is about grouping of functionality

(operations) and related data (attributes) together into a coherent data structure (classes).

  • Classes represent complex data types and the
  • perations that act on them. An object is a

particular instance of a class.

slide-8
SLIDE 8

Marcus Börger Introduction to Object-oriented programming with PHP 8

Encapsulation

  • Encapsulation is about grouping of functionality

(operations) and related data (attributes) together into a coherent data structure (classes).

  • Classes represent complex data types and the
  • perations that act on them. An object is a

particular instance of a class.

  • The basic idea is to re-code real life.

For instance, if you press a key on your laptop keyboard you do not know what is happening in detail. For you it is the same as if you press the keyboard of an ATM. We say the interface is the same. If another person has the same laptop the internal details would be exactly the same.

slide-9
SLIDE 9

Marcus Börger Introduction to Object-oriented programming with PHP 9

Encapsulation

  • Encapsulation is about grouping of functionality

(operations) and related data (attributes) together into a coherent data structure (classes).

  • Classes represent complex data types and the
  • perations that act on them. An object is a

particular instance of a class.

  • The basic idea is to re-code real life.

For instance, if you publish a text that is not really different from publishing a picture. Both are content types and you might want to encapsulate the details on how to do the actual publishing in a class. And once you have that you can easily have content that consists of both pictures and text and yet use the same operations for publishing. Then later you might publish tables using the same interface.

slide-10
SLIDE 10

Marcus Börger Introduction to Object-oriented programming with PHP 10

Encapsulation: Are Objects Just Dictionaries?

  • In PHP 4 objects were little more than arrays.
  • In PHP 5 you get much more control by visibility,

interfaces, type hints, interceptors and more.

  • Another difference is coherency. Classes can be

told to automatically execute specific code on

  • bject creation and destruction.

cl ass Si m pl e { f unct i on __const r uct ( ) { / * . . . * / } f unct i on __dest r uct ( ) { / * . . . * / } }

slide-11
SLIDE 11

Marcus Börger Introduction to Object-oriented programming with PHP 11

Data Hiding

  • Another difference between objects and arrays is

that objects permit strict visibility semantics. Data hiding eases refactoring by controlling what other parties can access in your code.

public anyone can access it protected

  • nly descendants can access it

private

  • nly you can access it

final no one can re-declare it abstract someone else will implement this Why have these in PHP? Because sometimes self-discipline isn’t enough.

slide-12
SLIDE 12

Marcus Börger Introduction to Object-oriented programming with PHP 12

Inheritance

  • Inheritance allows a class to specialize (or extend)

another class and inherit all its methods, properties and behaviors.

  • This promotes

Extensibility Reusability Code Consolidation Abstraction Responsibility

slide-13
SLIDE 13

Marcus Börger Introduction to Object-oriented programming with PHP 13

The Problem of Code Duplication

  • Code duplication contradicts maintainability.

You often end up with code that looks like this: f unct i on f oo_t o_xm l ( $f oo) { / / gener i c st uf f / / f oo- speci f i c st uf f } f unct i on bar _t o_xm l ( $bar ) { / / gener i c st uf f / / bar speci f i c st uf f }

slide-14
SLIDE 14

Marcus Börger Introduction to Object-oriented programming with PHP 14

The Problem of Code Duplication

  • You could clean that up as follows

f unct i on base_t o_xm l ( $dat a) { / * . . . * / } f unct i on f oo_t o_xm l ( $f oo) { base_t o_xm l ( $f oo) ; / / f oo speci f i c st uf f } f unct i on bar _t o_xm l ( $bar ) { base_t o_xm l ( $bar ) ; / / bar speci f i c st uf f }

  • But it’s hard to keep base_to_xml() working for

the disparate foo and bar types.

slide-15
SLIDE 15

Marcus Börger Introduction to Object-oriented programming with PHP 15

The Problem of Code Duplication

  • In an OOP style you would create classes for the

Foo and Bar classes that extend from a base class that handles common functionality.

  • Sharing a base class promotes sameness.

cl ass Bar ext ends Base { publ i c f unct i on t oXM L( ) { par ent : : t oXM L( ) ; / / bar speci f i c st uf f } } cl ass Base { publ i c f unct i on t oXM L( ) { / * . . . * / } } cl ass Foo ext ends Base { publ i c f unct i on t oXM L( ) { par ent : : t oXM L( ) ; / / f oo speci f i c st uf f } }

slide-16
SLIDE 16

Marcus Börger Introduction to Object-oriented programming with PHP 16

Polymorphism?

  • Suppose a calendar that is a collection of entries.

Procedurally dislpaying all the entries might look like: f or each( $ent r i es as $ent r y) { swi t ch( $ent r y[ ’ t ype’ ] ) { case ' pr of essi onal ' : di spl ay_pr of essi onal _ent r y( $ent r y) ; br eak; case ' per sonal ' : di spl ay_per sonal _ent r y( $ent r y) ; br eak; } }

slide-17
SLIDE 17

Marcus Börger Introduction to Object-oriented programming with PHP 17

Simplicity through Polymorphism

  • In the OOP paradigm this would look like:

f or each( $ent r i es as $ent r y) { $ent r y- >di spl ay( ) ; }

  • The key point is we don't have to modify this loop

to add new types. When we add a new type, that type gets a display() method so that it knows how to display itself, and we’re done.

  • Also this is much faster because we do not have to

check the type for every element.

slide-18
SLIDE 18

Marcus Börger Introduction to Object-oriented programming with PHP 18

Simplicity through Magic?

  • Actually in PHP you might want this:

f or each( $ent r i es as $ent r y) { echo $ent r y; }

  • A class can have a __t oSt r i ng( )

__t oSt r i ng( ) method which defines how its objects are converted into a textual representation.

  • PHP 5.2 supports this in all string contexts.
slide-19
SLIDE 19

Marcus Börger Introduction to Object-oriented programming with PHP 19

Polymorphism the other way round

  • Unlike other languages PHP does not and will not
  • ffer polymorphism for method calling. Thus the

following will never be available in PHP < ?php class Test { function toXML(Personal $obj) / / … function toXML(Professional $obj) / / … } ?>

  • To work around this

Use the other way round (call other methods from a single toXML() function in a polymorphic way) Use switch/ case (though this is not the OO way)

slide-20
SLIDE 20

Marcus Börger Introduction to Object-oriented programming with PHP 20

Another example

cl ass Hum ans { publ i c f unct i on __const r uct ( $nam e) { / * . . . * / } publ i c f unct i on eat ( ) { / * . . . * / } publ i c f unct i on sl eep( ) { / * . . . * / } publ i c f unct i on snor e( ) { / * . . . * / } publ i c f unct i on wakeup( ) { / * . . . * / } }

slide-21
SLIDE 21

Marcus Börger Introduction to Object-oriented programming with PHP 21

Some Inheritance

cl ass Hum ans { publ i c f unct i on __const r uct ( $nam e) { / * . . . * / } publ i c f unct i on eat ( ) { / * . . . * / } publ i c f unct i on sl eep( ) { / * . . . * / } publ i c f unct i on snor e( ) { / * . . . * / } publ i c f unct i on wakeup( ) { / * . . . * / } } cl ass W

  • m

en ext ends Hum ans { publ i c f unct i on gi veBi r t h( ) { / * . . . * / } }

slide-22
SLIDE 22

Marcus Börger Introduction to Object-oriented programming with PHP 22

Inheritance+ Polymorphism

cl ass Hum ans { publ i c f unct i on __const r uct ( $nam e) { / * . . . * / } publ i c f unct i on eat ( ) { / * . . . * / } publ i c f unct i on sl eep( ) { / * . . . * / } publ i c f unct i on wakeup( ) { / * . . . * / } } cl ass W

  • m

en ext ends Hum ans { publ i c f unct i on gi veBi r t h( ) { / * . . . * / } } cl ass M en ext ends Hum ans { publ i c f unct i on snor e( ) { / * . . . * / } }

slide-23
SLIDE 23

Marcus Börger Introduction to Object-oriented programming with PHP 23

A little abstraction

abst r act cl ass Hum ans { publ i c f unct i on __const r uct ( $nam e) { / * . . . * / } abst r act publ i c f unct i on gender ( ) ; publ i c f unct i on eat ( ) { / * . . . * / } publ i c f unct i on sl eep( ) { / * . . . * / } publ i c f unct i on wakeup( ) { / * . . . * / } } cl ass W

  • m

en ext ends Hum ans { publ i c f unct i on gender ( ) { r et ur n ' f em al e' ; } publ i c f unct i on gi veBi r t h( ) { / * . . . * / } } cl ass M en ext ends Hum ans { publ i c f unct i on gender ( ) { r et ur n ' m al e' ; } publ i c f unct i on snor e( ) { / * . . . * / } }

slide-24
SLIDE 24

Marcus Börger Introduction to Object-oriented programming with PHP 24

A little abstraction

abst r act cl ass Hum ans { publ i c f unct i on __const r uct ( $nam e) { / * . . . * / } abst r act publ i c f unct i on gender ( ) ; publ i c f unct i on eat ( ) { / * . . . * / } publ i c f unct i on sl eep( ) { / * . . . * / } publ i c f unct i on wakeup( ) { / * . . . * / } } cl ass W

  • m

en ext ends Hum ans { f i nal publ i c f unct i on gender ( ) { r et ur n ' f ' ; } publ i c f unct i on gi veBi r t h( ) { / * . . . * / } } cl ass M en ext ends Hum ans { f i nal publ i c f unct i on gender ( ) { r et ur n ' m ' ; } publ i c f unct i on snor e( ) { / * . . . * / } }

slide-25
SLIDE 25

Marcus Börger Introduction to Object-oriented programming with PHP 25

PHP and OOP

slide-26
SLIDE 26

Marcus Börger Introduction to Object-oriented programming with PHP 26

PHP 4 and OOP ?

  • Poor Object model

Methods

No visibility No abstracts, no final Static without declaration

Properties

No static properties No constants

Inheritance

No abstract, final inheritance, no interfaces No prototype checking, no types

Object handling

Copied by value No destructors

slide-27
SLIDE 27

Marcus Börger Introduction to Object-oriented programming with PHP 27

ZE2's revamped object model

  • Objects are referenced by identifiers
  • Constructors and Destructors
  • Static members
  • Constants
  • Visibility
  • Interfaces
  • Final and abstract members
  • Interceptors
  • Exceptions
  • Reflection API
  • Iterators
slide-28
SLIDE 28

Marcus Börger Introduction to Object-oriented programming with PHP 28

Revamped Object Model

  • PHP 5 has really good OOP support

Better code reuse Better for team development Easier to refactor Some patterns lead to much more efficient code Fits better in marketing scenarios

slide-29
SLIDE 29

Marcus Börger Introduction to Object-oriented programming with PHP 29

PHP 5 OOP in detail

slide-30
SLIDE 30

Marcus Börger Introduction to Object-oriented programming with PHP 30

Objects referenced by identifiers

  • Objects are no longer somewhat special arrays
  • Objects are no longer copied by default
  • Objects may be copied using clone/ __clone()

cl ass O bj ect { } ; $obj = new O bj ect ( ) ; $r ef = $obj ; $dup = cl one cl one $obj ; Class Object $obj $ref $dup Instance 1 Instance 2

slide-31
SLIDE 31

Marcus Börger Introduction to Object-oriented programming with PHP 31

Constructors and Destructors

  • Constructors/ Destructors control object lifetime

Constructors may have both new OR old style name

New style constructors are preferred Constructors must not use inherited protocol

Destructors are called when deleting the last reference

No particular or controllable order during shutdown Destructors cannot have parameters Since PHP 5.0.1 destructors can work with resources cl ass O bj ect { f unct i on __const r uct __const r uct ( ) { } f unct i on __dest r uct __dest r uct ( ) { } } $obj = new O bj ect ( ) ; unset ( $obj ) ;

slide-32
SLIDE 32

Marcus Börger Introduction to Object-oriented programming with PHP 32

Constructors and Destructors

  • Parents must be called manually

cl ass Base { f unct i on __const r uct ( ) { } f unct i on __dest r uct ( ) { } } cl ass O bj ect ext ends Base { f unct i on __const r uct ( ) { par ent par ent : : __const r uct ( ) ; } f unct i on __dest r uct ( ) { par ent par ent : : __dest r uct ( ) ; } } $obj = new O bj ect ( ) ; unset ( $obj ) ;

slide-33
SLIDE 33

Marcus Börger Introduction to Object-oriented programming with PHP 33

Default property values

  • Properties can have default values

Bound to the class not to the object Default values cannot be changed but overwritten cl ass O bj ect { var $pr op = " Hel l o\ n" ; } $obj 1 = new O bj ect ; $obj 1- >pr op = " Hel l o W

  • r l d\ n" ;

$obj 2 = new O bj ect ; echo $obj 2- >pr op; / / Hel l o

Class Object $prop/default $obj2 Instance 2 $prop $obj1 Instance 1 $prop

slide-34
SLIDE 34

Marcus Börger Introduction to Object-oriented programming with PHP 34

Static members

  • Static methods and properties

Bound to the class not to the object

Only exists once per class rather than per instance

Can be initialized cl ass O bj ect { var $pr op; st at i c st at i c $st at = " Hel l o\ n" ; st at i c st at i c f unct i on t est ( ) { echo sel f sel f : : $st at ; } } O bj ect : : t est ( ) ; $obj 1 = new O bj ect ; $obj 2 = new O bj ect ;

Class Object $stat $obj2 Instance 2 $prop $obj1 Instance 1 $prop

slide-35
SLIDE 35

Marcus Börger Introduction to Object-oriented programming with PHP 35

Pseudo constants

  • __CLASS__

__CLASS__ shows the current class name

  • __M

ETHO D__ __M ETHO D__ shows class and method or function

  • sel f

sel f references the class itself

  • par ent

par ent references the parent class

  • $t hi s

$t hi s references the object itself

cl ass Base { st at i c f unct i on Show( ) { echo __FI LE__. ' ( ' . __LI NE__. ' ) : ' . __M ETHO D__. " \ n" ; } } cl ass O bj ect ext ends Base { st at i c f unct i on Use( ) { Sel f : : Show( ) ; Par ent : : Show( ) ; } st at i c f unct i on Show( ) { echo __FI LE__. ' ( ' . __LI NE__. ' ) : ' . __M ETHO D__. " \ n" ; } }

slide-36
SLIDE 36

Marcus Börger Introduction to Object-oriented programming with PHP 36

Visibility

  • Controlling member visibility / Information hiding

A derived class doesn't know parents private members An inherited protected member can be made public

cl ass Base { publ i c publ i c $a; pr ot ect ed pr ot ect ed $b; pr i vat e pr i vat e $c; } cl ass Der i ved ext ends Base { publ i c publ i c $a; publ i c publ i c $b; pr i vat e pr i vat e $c; } Base $a $b $c Derived $a $b $c Base::$c

slide-37
SLIDE 37

Marcus Börger Introduction to Object-oriented programming with PHP 37

Constructor visibility

  • A protected constructor prevents instantiation

cl ass Base { pr ot ect ed f unct i on __const r uct ( ) { } } cl ass Der i ved ext ends Base { / / const r uct or i s st i l l pr ot ect ed st at i c f unct i on get Base( ) { r et ur n new Base; / / Fact or y pat t er n } } cl ass Thr ee ext ends Der i ved { publ i c f unct i on __const r uct ( ) { } }

slide-38
SLIDE 38

Marcus Börger Introduction to Object-oriented programming with PHP 38

The Singleton pattern

  • Sometimes you want only a single instance of

aclass to ever exist.

DB connections An object representing the user or connection.

cl ass Si ngl et on { st at i c pr i vat e $i nst ance; pr ot ect ed f unct i on __const r uct ( ) { } f i nal pr i vat e f unct i on __cl one( ) { } st at i c f unct i on get I nst ance( ) { i f ( ! sel f : : $i nst ance) sel f : : $i nst ance = new Si ngl et on( ) ; r et ur n sel f : : $i nst ance; } } $a = Si ngl et on: : get I nst ance( ) ; $a- >i d = 1; $b = Si ngl et on: : get I nst ance( ) ; pr i nt $b- >i d. " \ n" ;

slide-39
SLIDE 39

Marcus Börger Introduction to Object-oriented programming with PHP 39

Constants

  • Constants are read only static properties
  • Constants are always public

cl ass Base { const const gr eet i ng = " Hel l o\ n" ; } cl ass Der vi ed ext ends Base { const const gr eet i ng = " Hel l o W

  • r l d\ n" ;

st at i c f unct i on f unc( ) { echo par ent : : gr eet i ng; } } echo Base: : gr eet i ng; echo Der i ved: : gr eet i ng; Der i ved: : f unc( ) ;

slide-40
SLIDE 40

Marcus Börger Introduction to Object-oriented programming with PHP 40

Abstract members

  • Methods can be abstract

They don’t have a body A class with an abstract method must be abstract

  • Classes can be made abstract

The class cannot be instantiated

  • Properties cannot be made abstract

abst r act abst r act cl ass Base { abst r act abst r act f unct i on no_body( ) ; } cl ass Der i ved ext ends Base { f unct i on no_body( ) { echo " Body\ n" ; } }

slide-41
SLIDE 41

Marcus Börger Introduction to Object-oriented programming with PHP 41

Final members

  • Methods can be final

They cannot be overwritten They are class invariants

  • Classes can be final

They cannot be inherited

cl ass Base { f i nal f i nal f unct i on i nvar i ant ( ) { echo " Hel l o\ n" ; } } cl ass Der i ved ext ends Base { } f i nal f i nal cl ass Leaf ext ends Der i ved { }

slide-42
SLIDE 42

Marcus Börger Introduction to Object-oriented programming with PHP 42

  • Often different objects have the same interface

without having the same base class

cl ass Li ne { f unct i on dr aw( ) { } ; } cl ass Pol ygon { pr ot ect ed $l i nes; f unct i on dr aw( ) { f or each( $t hi s- >l i nes as $l i ne) $l i ne- >dr aw( ) ; } } cl ass Rect angl e ext ends Pol ygon { } cl ass El l i pse { f unct i on dr aw( ) { } ; } cl ass Ci r cl e ext ends El l i pse { f unct i on dr aw( ) { par ent : : dr aw( ) ; } }

Different Object same behavior

Polygon Line Ellipse Circle $lines Rectangle

slide-43
SLIDE 43

Marcus Börger Introduction to Object-oriented programming with PHP 43

Interfaces

  • Interfaces describe an abstract class protocol
  • Classes may inherit multiple Interfaces

i nt er f ace Dr awabl e { f unct i on dr aw( ) ; } cl ass Li ne i m pl em ent s Dr awabl e { f unct i on dr aw( ) { } ; } cl ass Pol ygon i m pl em ent s Dr awabl e { pr ot ect ed $l i nes; f unct i on dr aw( ) { f or each( $t hi s- >l i nes as $l i ne) $l i ne- >dr aw( ) ; } } cl ass Rect angl e ext ends Pol ygon { } cl ass El l i pse i m pl em ent s Dr awabl e { f unct i on dr aw( ) { } ; } cl ass Ci r cl e ext ends El l i pse { f unct i on dr aw( ) { par ent : : dr aw( ) ; } }

Drawable Polygon Line Ellipse Circle $lines Rectangle

slide-44
SLIDE 44

Marcus Börger Introduction to Object-oriented programming with PHP 44

Property kinds

  • Declared properties

May have a default value Can have selected visibility

  • Implicit public properties

Declared by simply using them in ANY method

  • Virtual properties

Handled by interceptor methods

  • Static properties

Bound to the class rather than to the instance

slide-45
SLIDE 45

Marcus Börger Introduction to Object-oriented programming with PHP 45

Object to String conversion

  • __toString(): semi-automatic object to string

conversion with echo and print (automatic starting with 5.2)

cl ass O bj ect { f unct i on __t oSt r i ng __t oSt r i ng( ) { r et ur n ' O bj ect as st r i ng' ; } } $o = new O bj ect ; echo $o; / / does cal l __t oSt r i ng $st r = ( st r i ng) $o; / / does cal l __t oSt r i ng

slide-46
SLIDE 46

Marcus Börger Introduction to Object-oriented programming with PHP 46

Interceptors

  • Allow to dynamically handle non class members

Lazy initialization of properties Simulating Object aggregation and Multiple inheritance

cl ass O bj ect { pr ot ect ed $vi r t ual = ar r ay( ) ; f unct i on __get __get ( $nam e) { r et ur n @ $t hi s- >vi r t ual [ $nam e] ; } f unct i on __set __set ( $nam e, $val ue) { $t hi s- >vi r t ual [ $nam e] = $val ue; } f unct i on __unset __unset ( $nam e) { unset ( $t hi s- >vi r t ual [ $nam e] ) ; } f unct i on __i sset __i sset ( $nam e) { r et ur n i sset ( $t hi s- >vi r t ual [ $nam e] ) ; } f unct i on __cal l __cal l ( $f unc, $par am s) { echo ' Coul d not cal l ' . __CLASS__ . ' : : ' . $f unc . " \ n" ; } }

slide-47
SLIDE 47

Marcus Börger Introduction to Object-oriented programming with PHP 47

Typehinting

  • PHP 5 allows to easily force a type of a parameter

PHP does not allow NULL for typehints Typehints must be inherited as given in base class PHP 5.1 offers typehinting with arrays PHP 5.2 offers optional typehinted parameters (= NULL)

cl ass O bj ect { publ i c f unct i on com par e( O bj ect $ot her ) { / / Som e code her e } publ i c f unct i on com par e2( $ot her ) { i f ( i s_nul l ( $ot her ) | | $ot her i nst anceof O bj ect ) { / / Som e code her e } } }

slide-48
SLIDE 48

Marcus Börger Introduction to Object-oriented programming with PHP 48

Class Design

  • It is important to think about your class hierarchy
  • Avoid very deep or broad inheritance graphs
  • PHP only supports is-a and has-a relations

Vehicle Truck Car Bus Diesel Gasoline Engine Bicycle Tires Turbine Tank Plane

slide-49
SLIDE 49

Marcus Börger Introduction to Object-oriented programming with PHP 49

Too Strict or too Weak?

  • PHP tries to prevent you from doing some errors

You are bound to keep inherited signatures You cannot change from ref to non-ref return

  • Yet PHP allows absolute flexibility

Just do not define a signature Warning: This is extremely error prone

slide-50
SLIDE 50

Marcus Börger Introduction to Object-oriented programming with PHP 50

Dynam ic class loading

slide-51
SLIDE 51

Marcus Börger Introduction to Object-oriented programming with PHP 51

Dynamic class loading

  • __aut ol oad( ) is good

Requires a single file for each class Only load class files when necessary

No need to parse/ compile unneeded classes No need to check which class files to load

Additional user space code Only one single loader model is possible

  • __aut ol oad( ) is good when you're alone
slide-52
SLIDE 52

Marcus Börger Introduction to Object-oriented programming with PHP 52

__aut ol oad & r equi r e_once

  • St or e t he cl ass l oader i n an i ncl ude f i l e

I n each scr i pt : r equi r e_once( ' <pat h>/ aut ol oad. i nc' ) Use I NI opt i on: aut o_pr epend_f i l e=<pat h>/ aut ol oad. i nc

<?php f unct i on __aut ol oad( $cl ass_nam e) { r equi r e_once( di r nam e( __FI LE__) . ' / ' . $cl ass_nam e . ' . p5c' ) ; } ?>

slide-53
SLIDE 53

Marcus Börger Introduction to Object-oriented programming with PHP 53

SPL's class loading

  • Supports fast default implementation

Look into path's specified by INI option include_path Look for specified file extensions (.inc, .php)

  • Ability to register multiple user defined loaders
  • Overwrites ZEND engine's __autoload() cache

You need to register __autoload if using spl's autoload

<?php spl _aut ol oad_r egi st er ( ' spl _aut ol oad' ) ; i f ( f unct i on_exi st s( ' __aut ol oad' ) ) { spl _aut ol oad_r egi st er ( ' __aut ol oad' ) ; } ?>

slide-54
SLIDE 54

Marcus Börger Introduction to Object-oriented programming with PHP 54

SPL's class loading

  • spl _aut ol oad( $cl ass_nam

e, $ext ensi ons=NULL) Load a class from a file in include path Fast c code implementation

  • spl _aut ol oad_ext ensi ons( $ext ensi ons=NULL)

Get or set filename extensions

  • spl _aut ol oad_r egi st er ( $l oader _f unct i on)

Register a single loader function

  • spl _aut ol oad_unr egi st er ( $l oader _f unct i on)

Unregister a single loader function

  • spl _aut ol oad_f unct i ons( )

List all registered loader functions

  • spl _aut ol oad_cal l ( $cl ass_nam

e) Load a class through registered class loaders Uses spl _aut ol oad( ) as fallback

slide-55
SLIDE 55

Marcus Börger Introduction to Object-oriented programming with PHP 55

Exceptions

slide-56
SLIDE 56

Marcus Börger Introduction to Object-oriented programming with PHP 56

Exceptions

  • Respect these rules
  • 1. Exceptions are exceptions
  • 2. Never use exceptions for control flow
  • 3. Never ever use exceptions for parameter passing

<?php t r y t r y { / / your code t hr ow t hr ow new Except i on( ) ; } cat ch cat ch ( Except i on $e) { / / except i on handl i ng } ?>

slide-57
SLIDE 57

Marcus Börger Introduction to Object-oriented programming with PHP 57

Exception specialization

  • Exceptions should be specialized
  • Exceptions should inherit built in class exception

cl ass Your Except i on ext ends Except i on { } t r y { / / your code t hr ow new Your Except i on( ) ; } cat ch ( Your Except i on $e) { / / except i on handl i ng } cat ch ( Except i on $e) { / / except i on handl i ng }

slide-58
SLIDE 58

Marcus Börger Introduction to Object-oriented programming with PHP 58

Exception specialization

  • Exception blocks can be nested
  • Exceptions can be re thrown

cl ass Your Except i on ext ends Except i on { } t r y { t r y { / / your code t hr ow new Your Except i on( ) ; } cat ch ( Your Except i on $e) { / / except i on handl i ng t hr ow $e; } cat ch ( Except i on $e) { / / except i on handl i ng } } cat ch ( Your Except i on $e) { / / except i on handl i ng }

slide-59
SLIDE 59

Marcus Börger Introduction to Object-oriented programming with PHP 59

Practical use of exceptions

  • Constructor failure
  • Converting errors/ warnings to exceptions
  • Simplify error handling
  • Provide additional error information by tagging
slide-60
SLIDE 60

Marcus Börger Introduction to Object-oriented programming with PHP 60

Constructor failure

  • In PHP 4.4 you would simply unset ( $t hi s)
  • Provide an argument to receive the error condition

<?php cl ass O bj ect { f unct i on __const r uct ( & $f ai l ur e) / / " O bj ect " i n PHP 4 { $f ai l ur e = t r ue; } } $er r or = f al se; $o = new O bj ect ( $er r or ) ; i f ( ! $er r or ) { / / er r or handl i ng, NO TE: t he obj ect was const r uct ed unset ( $o) ; } ?>

slide-61
SLIDE 61

Marcus Börger Introduction to Object-oriented programming with PHP 61

Constructor failure

  • In 5 constructors do not return the created object
  • Exceptions allow to handle failed constructors

<?php cl ass O bj ect { f unct i on __const r uct ( ) { t hr ow new Except i on; } } t r y { $o = new O bj ect ; } cat ch ( Except i on $e) { echo " O bj ect coul d not be i nst ant i at ed\ n" ; } ?>

slide-62
SLIDE 62

Marcus Börger Introduction to Object-oriented programming with PHP 62

Convert Errors to Exceptions

  • Implementing PHP 5.1 class ErrorException

<?php i f ( ! cl ass_exi st s( ' Er r or Except i on' , f al se) ) { cl ass Er r or Except i on ext ends Except i on { pr ot ect ed $sever i t y; f unct i on __const r uct ( $m sg, $code, $er r no, $f i l e, $l i ne) { par ent : : __const r uct ( $m sg, $code) ; $t hi s- >sever i t y = $er r no; $t hi s- >f i l e = $f i l e; $t hi s- >l i ne = $l i ne; } f unct i on get Sever i t y( ) { r et ur n $t hi s- >sever i t y; } } } ?>

slide-63
SLIDE 63

Marcus Börger Introduction to Object-oriented programming with PHP 63

Convert Errors to Exceptions

  • Implementing the error handler

<?php f unct i on Er r or sToExcept i ons( $er r no, $m sg, $f i l e, $l i ne) { t hr ow new Er r or Except i on( $m sg, 0, $er r no, $f i l e, $l i ne) ; } set _er r or _handl er ( ' Er r or sToExcept i ons' ) ; ?>

slide-64
SLIDE 64

Marcus Börger Introduction to Object-oriented programming with PHP 64

Simplify error handling

  • Typical database access code contains lots of if's

<ht m l ><body> <?php $ok = f al se; $db = new PDO ( ' CO NNECTI O N' ) ; i f ( $db) { $r es = $db- >quer y( ' SELECT dat a' ) ; i f ( $r es) { $r es2 = $db- >quer y( ' SELECT ot her ' ) ; i f ( $r es2) { / / handl e dat a $ok = t r ue; / / onl y i f al l went ok } } } i f ( ! $ok) echo ' <h1>Ser vi ce cur r ent l y unavai l abl e</ h1>' ; ?> </ body></ ht m l >

slide-65
SLIDE 65

Marcus Börger Introduction to Object-oriented programming with PHP 65

Simplify error handling

  • Trade code simplicity with a new complexity

<ht m l ><body> <?php t r y { $db = new PDO ( ' CO NNECTI O N' ) ; $db- >set At t r i but e( PDO : : ATTR_ERRM O DE, PDO : : ERRM O DE_EXCEPTI O N) ; $r es = $db- >quer y( ' SELECT dat a' ) ; $r es2 = $db- >quer y( ' SELECT ot her ' ) ; / / handl e dat a } cat ch ( Except i on $e) { echo ' <h1>Ser vi ce cur r ent l y unavai l abl e</ h1>' ; er r or _l og( $e- >get M essage( ) ) ; } ?> </ body></ ht m l >

slide-66
SLIDE 66

Marcus Börger Introduction to Object-oriented programming with PHP 66

SPL Exceptions

  • SPL provides a standard set of exceptions
  • Class Exception must be the root of all exceptions
slide-67
SLIDE 67

Marcus Börger Introduction to Object-oriented programming with PHP 67

General distinguishing

  • Logi cExcept i on

Anything that could have been detected at compile time, during application design

  • r by the good old technology:

"look closely"

  • Runt i m

eExcept i on Anything that is unexpected during runtime Base Exception for all database extensions

slide-68
SLIDE 68

Marcus Börger Introduction to Object-oriented programming with PHP 68

LogicException

  • Function not found or similar

BadM et hodCal l Except i on

  • Value not in allowed domain
  • Argument not valid
  • Length exceeded
  • Some index is out of range
slide-69
SLIDE 69

Marcus Börger Introduction to Object-oriented programming with PHP 69

RunTimeException

  • An actual value is out of bounds
  • Buffer or other overflow situation
  • Value outside expected range
  • Buffer or other underflow situation
  • Any other unexpected values
slide-70
SLIDE 70

Marcus Börger Introduction to Object-oriented programming with PHP 70

Overloading __call

  • If using __call, ensure only valid calls are made

abst r act cl ass M yI t er at or W r apper i m pl em ent s I t er at or { f unct i on __const r uct ( I t er at or $i t ) { $t hi s- >i t = $i t ; } f unct i on __cal l ( $f unc, $ar gs) { $cal l ee = ar r ay( $t hi s- >i t , $f unc) ; i f ( ! i s_cal l abl e( $cal l ee) ) { t hr ow new BadM et hodCal l Except i on( ) ; } r et ur n cal l _user _f unc_ar r ay( $cal l ee, $ar gs) ; } }

Compile-Time: Error in design

slide-71
SLIDE 71

Marcus Börger Introduction to Object-oriented programming with PHP 71

Interfaces and __call

  • Interface functions cannot be handled by __call
  • Either mark the class abstract...

abst r act

cl ass M yI t er at or W r apper i m pl em ent s I t er at or { f unct i on __const r uct ( I t er at or $i t ) { $t hi s- >i t = $i t ; } f unct i on __cal l ( $f unc, $ar gs) { $cal l ee = ar r ay( $t hi s- >i t , $f unc) ; i f ( ! i s_cal l abl e( $cal l ee) ) { t hr ow new BadM et hodCal l Except i on( ) ; } r et ur n cal l _user _f unc_ar r ay( $cal l ee, $ar gs) ; } } } I nt er f ace I t er at or { f unct i on r ewi nd( ) ; f unct i on val i d( ) ; f unct i on cur r ent ( ) ; f unct i on key( ) ; f unct i on next ( ) ;

slide-72
SLIDE 72

Marcus Börger Introduction to Object-oriented programming with PHP 72

Interfaces and __call

  • Interface functions cannot be handled by __call
  • ...or provide the functions (here as proxy/ forward)

cl ass M yI t er at or W r apper i m pl em ent s I t er at or { f unct i on __const r uct ( I t er at or $i t ) { $t hi s- >i t = $i t ; } f unct i on __cal l ( $f unc, $ar gs) { $cal l ee = ar r ay( $t hi s- >i t , $f unc) ; i f ( ! i s_cal l abl e( $cal l ee) ) { t hr ow new BadM et hodCal l Except i on( ) ; } r et ur n cal l _user _f unc_ar r ay( $cal l ee, $ar gs) ; } f unct i on r ewi nd( ) { $t hi s- >i t - >r ewi nd( ) ; } f unct i on val i d( ) { r et ur n $t hi s- >i t - >val i d( ) ; } f unct i on cur r ent ( ) { r et ur n $t hi s- >i t - >cur r ent ( ) ; } f unct i on key( ) { r et ur n $t hi s- >i t - >key( ) ; } f unct i on next ( ) { $t hi s- >i t - >next ( ) ; } } } I nt er f ace I t er at or { f unct i on r ewi nd( ) ; f unct i on val i d( ) ; f unct i on cur r ent ( ) ; f unct i on key( ) ; f unct i on next ( ) ;

slide-73
SLIDE 73

Marcus Börger Introduction to Object-oriented programming with PHP 73

Expecting formatted data

  • Opening a file for reading

$f o = new Spl Fi l eO bj ect ( $f i l e) ; $f o- >set Fl ags( Spl Fi l eO bj ect : : DRO P_NEW LI NE) ; $dat a = ar r ay( ) ; Run-Time: File might not be accessible or exist

slide-74
SLIDE 74

Marcus Börger Introduction to Object-oriented programming with PHP 74

Expecting formatted data

  • Reading a formatted file line by line

$f o = new Spl Fi l eO bj ect ( $f i l e) ; $f o- >set Fl ags( Spl Fi l eO bj ect : : DRO P_NEW LI NE) ; $dat a = ar r ay( ) ; f or each( $f o as $l ) { i f ( / * * * CHECK DATA * * * / ) { t hr ow new Except i on( ) ; } $dat a[ ] = $l ; }

  • ! pr eg_m

at ch( $r egex, $l ) Unexpect Val ueExcept i on

  • count ( $l =spl i t ( ' , ' ,

$l ) ) ! = 3 RangeExcept i on

  • count ( $dat a) > 100

O ver f l owExcept i on Run-Time: File might not be accessible or exist Run-Time: data is different for every execution

slide-75
SLIDE 75

Marcus Börger Introduction to Object-oriented programming with PHP 75

Expecting formatted data

  • Cehcking data after pre-processing

$f o = new Spl Fi l eO bj ect ( $f i l e) ; $f o- >set Fl ags( Spl Fi l eO bj ect : : DRO P_NEW LI NE) ; $dat a = ar r ay( ) ; f or each( $f o as $l ) { i f ( ! pr eg_m at ch( ' / \ d, \ d/ ' , $l ) ) { t hr ow new Unexpect edVal ueExcept i on( ) ; } $dat a[ ] = $l ; } / / Checks af t er t he f i l e was r ead ent i r el y

  • i f ( count ( $dat a) < 10)

t hr ow new Under f l owExcept i on( ) ;

  • i f ( count ( $dat a) > 99)

t hr ow new O ver f l owExcept i on( ) ;

  • i f ( count ( $dat a) < 10 | | count ( $dat a) > 99)

t hr ow new O ut O f BoundsExcept i on( ) ; Run-Time: data is different for every execution Run-Time: Filemight not be accessible or exist

slide-76
SLIDE 76

Marcus Börger Introduction to Object-oriented programming with PHP 76

Expecting formatted data

  • Processing pre-checked data

$f o = new Spl Fi l eO bj ect ( $f i l e) ; $f o- >set Fl ags( Spl Fi l eO bj ect : : DRO P_NEW LI NE) ; $dat a = ar r ay( ) ; f or each( $f o as $l ) { i f ( ! pr eg_m at ch( ' / \ d, \ d/ ' , $l ) ) { t hr ow new Unexpect edVal ueExcept i on( ) ; } $dat a[ ] = $l ; } i f ( count ( $dat a) < 10) t hr ow new Under f l owExcept i on( ) ; / / m aybe m

  • r e pr ecessi ng code

f or each( $dat a as &$v) { i f ( count ( $v) == 2) { t hr ow new Dom ai nExcept i on( ) ; } $v = $v[ 0] * $v[ 1] ; } Compile-Time: exception signals failed precondition Run-Time: data is different for every execution Run-Time: File might not be accessible or exist

slide-77
SLIDE 77

Marcus Börger Introduction to Object-oriented programming with PHP 77

Reflection

slide-78
SLIDE 78

Marcus Börger Introduction to Object-oriented programming with PHP 78

Reflection API

  • Can reflect nearly all aspects of your PHP code

Functions Classes, Methods, Properties Extensions

cl ass Foo { publ i c $pr op; f unct i on Func( $nam e) { echo " Hel l o $nam e" ; } } Ref l ect i onCl ass: : expor t ( ' Foo' ) ; Ref l ect i onO bj ect : : expor t ( new Foo) ; Ref l ect i onM et hod: : expor t ( ' Foo' , ' f unc' ) ; Ref l ect i onPr oper t y: : expor t ( ' Foo' , ' pr op' ) ; Ref l ect i onExt ensi on: : expor t ( ' st andar d' ) ;

slide-79
SLIDE 79

Marcus Börger Introduction to Object-oriented programming with PHP 79

Dynamic object creation

  • Reflection allows dynamic object creation

cl ass Test { f unct i on __const r uct ( $x, $y = NULL) { $t hi s- >x = $x; $t hi s- >y = $y; } } f unct i on new_obj ect _ar r ay( $cl s, $ar gs = NULL) { r et ur n cal l _user _f unc_ar r ay( ar r ay( new Ref l ect i onCl ass( $cl s) , ' newI nst ance' ) , $ar gs) ; } new_obj ect _ar r ay( ' st dCl ass' ) ; new_obj ect _ar r ay( ' Test ' , ar r ay( 1) ) ; new_obj ect _ar r ay( ' Test ' , ar r ay( 1, 2) ) ;

slide-80
SLIDE 80

Marcus Börger Introduction to Object-oriented programming with PHP 80

Built-in I nterfaces

slide-81
SLIDE 81

Marcus Börger Introduction to Object-oriented programming with PHP 81

Built-in Interfaces

  • PHP 5 contains built-in interfaces that allow you to

change the way the engine treats objects.

Ar r ayAccess I t er at or I t er at or Aggr egat e

  • Built-in extension SPL provides more Interfaces

and Classes

Ar r ayO bj ect , Ar r ayI t er at or Fi l t er I t er at or Recur si veI t er at or Use CLI: php - - r e SPL php - - r c Ar r ayAccess

slide-82
SLIDE 82

Marcus Börger Introduction to Object-oriented programming with PHP 82

ArrayAccess

  • Allows for creating objects that can be

transparently accessed by array syntax.

  • When combined with the iterator interface, it

allows for creating ‘arrays with special properties’.

i nt er f ace Ar r ayAccess { / / @ r et ur n whet her $of f set i s val i d ( t r ue/ f al se) f unct i on of f set Exi st s( $of f set ) ; / / @ r et ur n t he val ue associ at ed wi t h $of f set f unct i on of f set G et ( $of f set ) ; / / associ at e $val ue wi t h $of f set ( st or e t he dat a) f unct i on of f set Set ( $of f set , $val ue) ; / / unset t he dat a associ at ed wi t h $of f set f unct i on of f set Unset ( $of f set ) ; }

slide-83
SLIDE 83

Marcus Börger Introduction to Object-oriented programming with PHP 83

ArrayAccess

  • ArrayAccess does not allow references

(the following is an error)

cl ass M yAr r ay ext ends Ar r ayAccess { f unct i on &of f set G et ( $of f set ) { / * . . . * / } f unct i on of f set Set ( $of f set , &$val ue) { / * . . . * / } f unct i on of f set Exi st s( $of f set ) { / * . . . * / } f unct i on of f set Unset ( $of f set ) { / * . . . * / } }

slide-84
SLIDE 84

Marcus Börger Introduction to Object-oriented programming with PHP 84

ArrayAccess Example

  • We want to create variables which can be shared

between processes.

  • We will set up interception so that access attempts
  • n the variable are actually performed through a

DBM file.

slide-85
SLIDE 85

Marcus Börger Introduction to Object-oriented programming with PHP 85

Binding Access to a DBM

<?php cl ass DbaReader i m pl em ent s Ar r ayAccess { pr ot ect ed $db = NULL; f unct i on __const r uct ( $f i l e, $handl er ) { i f ( ! $t hi s- >db = dba_open( $f i l e, ' cd' , $handl er ) ) t hr ow new except i on( ' Coul d not open f i l e ' . $f i l e) ; } f unct i on __dest r uct ( ) { dba_cl ose( $t hi s- >db) ; } f unct i on of f set Exi st s( $of f set ) { r et ur n dba_exi st s( $of f set , $t hi s- >db) ; } f unct i on of f set G et ( $of f set ) { r et ur n dba_f et ch( $of f set , $t hi s- >db) ; } f unct i on of f set Set ( $of f set , $val ue) { r et ur n dba_r epl ace( $of f set , $val ue, $t hi s- >db) ; } f unct i on of f set Unset ( $of f set ) { r et ur n dba_del et e( $of f set , $t hi s- >db) ; } } ?>

slide-86
SLIDE 86

Marcus Börger Introduction to Object-oriented programming with PHP 86

A Trivial Example

<?php i f ( ! cl ass_exi st s( ' DbaReader ' , f al se) ) { r equi r e_once ‘ dbadeader . i nc’ ; } $_SHARED = new DbaReader ( ' / t m p/ . count er ' , ' f l at f i l e' ) ; $_SHARED[ ' count er ' ] += 1; pr i nt f ( " PI D: % d\ nCO UNTER: % d\ n" , get m ypi d( ) , $_SHARED[ ' count er ' ] ) ; ?>

slide-87
SLIDE 87

Marcus Börger Introduction to Object-oriented programming with PHP 87

Iterators

  • Normal objects behave like arrays when used with

the foreach construct

  • Specialized Iterator objects can be iterated

differently

<?php cl ass O bj ect { publ i c $pr op1 = " Hel l o " ; publ i c $pr op2 = " W

  • r l d\ n" ;

} f or each( new O bj ect as $pr op) { echo $pr op; } ?>

slide-88
SLIDE 88

Marcus Börger Introduction to Object-oriented programming with PHP 88

What are Iterators

  • Iterators are a concept to iterate anything that

contains other things.

  • Iterators allow to encapsulate algorithms
slide-89
SLIDE 89

Marcus Börger Introduction to Object-oriented programming with PHP 89

What are Iterators

  • Iterators are a concept to iterate anything that

contains other things. Examples:

Values and Keys in an array Ar r ayO bj ect , Ar r ayI t er at or Text lines in a file Spl Fi l eO bj ect Files in a directory [ Recur si ve] Di r ect or yI t er at or XML Elements or Attributes ext: SimpleXML, DOM Database query results ext: PDO, SQLite, MySQLi Dates in a calendar range PECL/ date (?) Bits in an image ?

  • Iterators allow to encapsulate algorithms
slide-90
SLIDE 90

Marcus Börger Introduction to Object-oriented programming with PHP 90

What are Iterators

  • Iterators are a concept to iterate anything that

contains other things. Examples:

Values and Keys in an array Ar r ayO bj ect , Ar r ayI t er at or Text lines in a file Spl Fi l eO bj ect Files in a directory [ Recur si ve] Di r ect or yI t er at or XML Elements or Attributes ext: SimpleXML, DOM Database query results ext: PDO, SQLite, MySQLi Dates in a calendar range PECL/ date (?) Bits in an image ?

  • Iterators allow to encapsulate algorithms

Classes and Interfaces provided by SPL:

AppendI t er at or , Cachi ngI t er at or , Li m i t I t er at or , Fi l t er I t er at or , Em pt yI t er at or , I nf i ni t eI t er at or , NoRewi ndI t er at or , O ut er I t er at or , Par ent I t er at or , Recur si veI t er at or , Recur si veI t er at or I t er at or , Seekabl eI t er at or , Spl Fi l eO bj ect , . . .

slide-91
SLIDE 91

Marcus Börger Introduction to Object-oriented programming with PHP 91

Array vs. Iterator

  • An array in PHP

$ar = ar r ay( ) can be rewound: r eset ( $ar ) is valid unless it's key is NULL: ! i s_nul l ( key( $ar ) ) have current values: cur r ent ( $ar ) have keys: key( $ar ) can be forwarded: next ( $ar )

  • Something that is traversable

$i t = new I t er at or ; m ay know how to be rewound: $i t - >r ewi nd( )

( does not r et ur n t he el em ent )

should know if there is a value: $i t - >val i d( ) m ay have a current value: $i t - >cur r ent ( ) m ay have a key: $i t - >key( )

( m ay r et ur n NULL at any t i m e)

can forward to its next element: $i t - >next ()

slide-92
SLIDE 92

Marcus Börger Introduction to Object-oriented programming with PHP 92

The big difference

  • Arrays

require memory for all elements allow to access any element directly

  • I terators
  • nly know one element at a time
  • nly require memory for the current element

forward access only Access done by method calls

  • Containers

require memory for all elements allow to access any element directly can create external Iterators or are internal Iterators

slide-93
SLIDE 93

Marcus Börger Introduction to Object-oriented programming with PHP 93

The basic concepts

  • Iterators can be internal or external

also referred to as active or passive

  • An internal iterator modifies the object itself
  • An external iterator points to another object

without modifying it

  • PHP always uses external iterators at engine-level
  • Iterators may iterate over other iterators
slide-94
SLIDE 94

Marcus Börger Introduction to Object-oriented programming with PHP 94

PHP Iterators

  • Anything that can be iterated implements Tr aver sabl e

Tr aver sabl e

  • Objects implementing Tr aver sabl e

Tr aver sabl e can be used in f or each f or each

  • User classes cannot implement Tr aver sabl e

Tr aver sabl e

  • I t er at or Aggr egat e

I t er at or Aggr egat e is for objects that use external iterators

  • I t er at or

I t er at or is for internal traversal or external iterators

IteratorAggregate + getIterator () : Iterator Traversable Iterator + + + + + rewind () valid () current () key () next () : void : boolean : mixed : mixed : void

slide-95
SLIDE 95

Marcus Börger Introduction to Object-oriented programming with PHP 95

Implementing Iterators

Traversable IteratorAggregate + getIterator () : Iterator Iterator + + + + + rewind () valid () current () key () next () : void : boolean : mixed : mixed : void AggregateImpl + <<Implement>> getIterator () : Iterator IteratorImpl + + + + + <<Implement>> <<Implement>> <<Implement>> <<Implement>> <<Implement>> rewind () valid () current () key () next () : void : boolean : mixed : mixed : void

slide-96
SLIDE 96

Marcus Börger Introduction to Object-oriented programming with PHP 96

How Iterators work

  • Iterators can be used manually
  • Iterators can be used implicitly with foreach

<?php $o = new Ar r ayI t er at or ( ar r ay( 1, 2, 3) ) ; $o- >r ewi nd( ) ; whi l e ( $o- >val i d( ) ) { $key = $o- >key( ) ; $val = $o- >cur r ent ( ) ; / / som e code $o- >next ( ) ; } ?> <?php $o = new Ar r ayI t er at or ( ar r ay( 1, 2, 3) ) ; f or each( $o as $key => $val ) { / / som e code } ?>

slide-97
SLIDE 97

Marcus Börger Introduction to Object-oriented programming with PHP 97

< ?php $it = get_resource(); for ($it-> rewind(); $it-> valid(); $it-> next()) { $value = $it-> current(); $key = $it-> key(); } ?>

How Iterators work

  • Internal Iterators
  • User Iterators

< ?php interface Iterator { function rewind(); function valid(); function current(); function key(); function next(); } ?>

slide-98
SLIDE 98

Marcus Börger Introduction to Object-oriented programming with PHP 98

  • Internal Iterators
  • User Iterators

< ?php $it = get_resource(); foreach($it as $key= > $val) { / / access data } ?> < ?php interface Iterator { function rewind(); function valid(); function current(); function key(); function next(); } ?>

How Iterators work

slide-99
SLIDE 99

Marcus Börger Introduction to Object-oriented programming with PHP 99

< ?php $it = get_resource(); foreach(new Filter($it, $filter_param) as $key= > $val) { / / access filtered data only } ?> < ?php class FilterIterator implements Iterator { function __construct(Iterator $input)... function rewind()... function accept()... function valid()... function current()... function key()... function next()... } ?>

How Iterators work

  • Internal Iterators
  • User Iterators

< ?php interface Iterator { function rewind(); function valid(); function current(); function key(); function next(); } ?>

slide-100
SLIDE 100

Marcus Börger Introduction to Object-oriented programming with PHP 100

Debug Session

<?php cl ass Ar r ayI t er at or { pr ot ect ed $ar ; f unct i on __const r uct ( Ar r ay $ar ) { $t hi s- >ar = $ar ; } f unct i on r ewi nd( ) { r ewi nd( $t hi s- >ar ) ; } f ucnt i on val i d( ) { r et ur n ! i s_nul l ( key( $t hi s- >ar ) ) ; } f unct i on key( ) { r et ur n key( $t hi s- >ar ) ; } f ucnt i on cur r ent ( ) { r et ur n cur r ent ( $t hi s- >ar ) ; } f unct i on next ( ) { next ( $t hi s- >ar ) ; } } ?> <?php $a = ar r ay( 1, 2, 3) ; $o = new Ar r ayI t er at or ( $a) ; f or each( $o as $key => $val ) { echo " $key => $va\ n" ; } ?> 0 => 1 1 => 2 2 => 3

PHP 5.1

slide-101
SLIDE 101

Marcus Börger Introduction to Object-oriented programming with PHP 101

  • Why not just use arrays:

f or each( $som e_ar r ay as $i t em ) { / * . . . * / }

  • Aren't we making life more difficult than need be?
  • No! For simple aggregations the above works fine

(though it’s slow), but not everything is an array. What about:

Buffered result sets Lazy Initialization Directories Anything not already an array

Aren’t Iterators Pointless in PHP?

slide-102
SLIDE 102

Marcus Börger Introduction to Object-oriented programming with PHP 102

Iterators by example

  • Using Iterators you can efficiently grab all groups

from INI files

  • The building blocks:

A class that handles INI files An abstract filter Iterator A filter that filters group names from the INI file input An Iterator to read all entries in the INI file Another filter that allow to search for specific groups

slide-103
SLIDE 103

Marcus Börger Introduction to Object-oriented programming with PHP 103

INI file abstraction

cl ass DbaReader i m pl em ent s I t er at or { pr ot ect ed $db = NULL; pr i vat e $key = f al se, $val = f al se; f unct i on __const r uct ( $f i l e, $handl er ) { i f ( ! $t hi s- >db = dba_open( $f i l e, ' r ' , $handl er ) ) t hr ow new Except i on( " Coul d not open f i l e $f i l e" ) ; } f unct i on __dest r uct ( ) { dba_cl ose( $t hi s- >db) ; } pr i vat e f unct i on f et ch_dat a( $key) { i f ( ( $t hi s- >key = $key) ! == f al se) $t hi s- >val = dba_f et ch( $t hi s- >key, $t hi s- >db) ; } f unct i on r ewi nd( ) { $t hi s- >f et ch_dat a( dba_f i r st key( $t hi s- >db) ) ; } f unct i on next ( ) { $t hi s- >f et ch_dat a( dba_next key( $t hi s- >db) ) ; } f unct i on cur r ent ( ) { r et ur n $t hi s- >val ; } f unct i on val i d( ) { r et ur n $t hi s- >key ! == f al se; } f unct i on key( ) { r et ur n $t hi s- >key; } }

slide-104
SLIDE 104

Marcus Börger Introduction to Object-oriented programming with PHP 104

Filtering Iterator keys

FilterIteraor is an abstract class

Abstract accept() is called from rewind() and next()

When accept() returns false next() will be called automatically

<?php cl ass KeyFi l t er ext ends Fi l t er I t er at or { pr i vat e $r x; f unct i on __const r uct ( I t er at or $i t , $r egex) { par ent : : __const r uct ( $i t ) ; $t hi s- >r x = $r egex; } f unct i on accept ( ) { r et ur n er eg( $t hi s- >r x, $t hi s- >get I nner I t er at or ( ) - >key( ) ) ; } f unct i on get Regex( ) { r et ur n $t hi s- >r x; } pr ot ect ed f unct i on __cl one( $t hat ) { / / di sal l ow cl one } } ?>

slide-105
SLIDE 105

Marcus Börger Introduction to Object-oriented programming with PHP 105

Getting only INI groups

<?php i f ( ! cl ass_exi st s( ' KeyFi l t er ' , f al se) ) { r equi r e_once( ' keyf i l t er . i nc' ) ; } cl ass I ni G r oups ext ends KeyFi l t er { f unct i on __const r uct ( $f i l e) { par ent : : __const r uct ( new DbaReader ( $f i l e, ' i ni f i l e' ) , ' ^\ [ . * \ ] $' ) ; } f unct i on cur r ent ( ) { r et ur n subst r ( par ent : : key( ) , 1, - 1) ; } f unct i on key( ) { r et ur n subst r ( par ent : : key( ) , 1, - 1) ; } } ?>

slide-106
SLIDE 106

Marcus Börger Introduction to Object-oriented programming with PHP 106

Putting it to work

<?php i f ( ! cl ass_exi st s( ' KeyFi l t er ' , f al se) ) { r equi r e_once( ' keyf i l t er . i nc' ) ; } i f ( ! cl ass_exi st s( ' I ni G r oups' , f al se) ) { r equi r e_once( ' i ni gr oups. i nc' ) ; } $i t = new I ni G r oups( $ar gv[ 1] ) ; i f ( $ar gc>2) { $i t = new KeyFi l t er ( $i t , $ar gv[ 2] ) ; } f or each( $i t as $gr oup) { echo $gr oup . " \ n" ; } ?>

Avoid calling __aut ol oad( )

slide-107
SLIDE 107

Marcus Börger Introduction to Object-oriented programming with PHP 107

Conclusion so far

  • Iterators require a new way of programming
  • Iterators allow to implement algorithms

abstracted from data

  • Iterators promote code reuse
  • Some things are already in SPL

Filtering Handling recursion Limiting

slide-108
SLIDE 108

Marcus Börger Introduction to Object-oriented programming with PHP 108

Design Patterns

slide-109
SLIDE 109

Marcus Börger Introduction to Object-oriented programming with PHP 109

Let’s Talk About Patterns

  • Patterns catalog solutions to problem categories
  • They consist of

A name A description of their problem A description of the solution An assessment of the pros and cons of the pattern

slide-110
SLIDE 110

Marcus Börger Introduction to Object-oriented programming with PHP 110

  • Not so much.

Patterns sources outside OOP include:

  • Architecture (the originator of the paradigm)
  • User Interface Design (wizards, cookie crumbs,

tabs)

  • Cooking (braising, pickling)

What do patterns have to do with OOP?

slide-111
SLIDE 111

Marcus Börger Introduction to Object-oriented programming with PHP 111

Patterns We’ve Seen So Far

  • Singleton Pattern
  • Iterator Pattern
  • Factory Pattern
slide-112
SLIDE 112

Marcus Börger Introduction to Object-oriented programming with PHP 112

Aggregator Pattern

  • Problem : You have collections of items that you
  • perate on frequently with lots of repeated code.

Remember our calendars:

f or each( $ent r i es as $ent r y) { echo $ent r y; }

  • Solution: Create a container that implements the

same interface, and perfoms the iteration for you.

slide-113
SLIDE 113

Marcus Börger Introduction to Object-oriented programming with PHP 113

Aggregator Pattern

cl ass Ent r yAggr egat e ext ends Ent r y { pr ot ect ed $ent r i es; . . . publ i c f unct i on di spl ay( ) { f or each( $t hi s- >ent r i es as $ent r y) { $ent r y- >di spl ay( ) ; } publ i c f unct i on add( Ent r y $e) { ar r ay_push( $t hi s- >ent r i es, $e) ; } }

  • By extending Entry, the aggregate can actually

stand in any place that entry did, and can itself contain other aggregated collections.

slide-114
SLIDE 114

Marcus Börger Introduction to Object-oriented programming with PHP 114

Proxy Pattern

  • Problem : You need to provide access to an
  • bject, but it has an interface you don’t know at

compile time.

  • Solution: Use accessor/ method overloading to

dynamically dispatch methods to the object.

  • Discussion: This is very typical of RPC-type

facilities like SOAP where you can interface with the service by reading in a definitions file of some sort at runtime.

slide-115
SLIDE 115

Marcus Börger Introduction to Object-oriented programming with PHP 115

Proxy Pattern in PEAR SOAP

<?php cl ass SO AP_Cl i ent { publ i c $wsdl ; publ i c f unct i on __const r uct ( $endpoi nt ) { $t hi s- >wsdl = W SDLM anager : : get ( $endpoi nt ) ; } publ i c f unct i on __cal l ( $m et hod, $ar gs) { $por t = $t hi s- >wsdl - >get Por t For O per at i on( $m et hod) ; $t hi s- >endpoi nt =$t hi s- >wsdl - >get Por t Endpoi nt ( $por t ) ; $r equest = SO AP_Envel ope: : r equest ( $t hi s- >wsdl ) ; $r equest - >addM et hod( $m et hod, $ar gs) ; $dat a = $r equest - >saveXM L( ) ; r et ur n SO AP_Envel ope: : par se( $t hi s- >endpoi nt , $dat a) ; } } ?>

slide-116
SLIDE 116

Marcus Börger Introduction to Object-oriented programming with PHP 116

Observer Pattern

  • Problem : You want an object to automatically

notify dependents when it is updated.

  • Solution: Allow 'observer' to register themselves

with the observable object.

  • Discussion: An object may not apriori know who

might be interested in it. The Observer pattern allows objects to register their interest and supply a notification method.

slide-117
SLIDE 117

Marcus Börger Introduction to Object-oriented programming with PHP 117

Object handling side notes

  • You cannot access the object identifier/ handle

$obser ver s[ ] = $obser ver ;

  • YOU need to prevent double insertion/ execution

f or each( $obser ver s as $o) { i f ( $o === $obser ver ) r et ur n; } $obser ver s[ ] = $obser ver ;

  • No easy way to delete an object from an array

f or each( $obser ver s as $k => $o) { i f ( $o === $obser ver ) { unset ( $obser ver [ $k] ) ; br eak; } }

slide-118
SLIDE 118

Marcus Börger Introduction to Object-oriented programming with PHP 118

Object Storage

cl ass O bj ect St or age { pr ot ect ed $st or age = ar r ay( ) ; f unct i on at t ach( $obj ) { f or each( $t hi s- >st or age as $o) { i f ( $o === $obj ) r et ur n; } $t hi s- >st or age[ ] = $obj ; } f unct i on det at ch( $obj ) { f or each( $t hi s- >st or age as $k => $o) { i f ( $o === $obj ) { unset ( $t hi s- >st or age[ $k] ) ; r et ur n; } } } }

slide-119
SLIDE 119

Marcus Börger Introduction to Object-oriented programming with PHP 119

Object Storage in 5.2

cl ass O bj ect St or age { pr ot ect ed $st or age = ar r ay( ) ; f unct i on at t ach( $obj ) { $t hi s- >st or age[ spl _obj ect _hash( $obj ) ] = $obj ; } f unct i on det at ch( $obj ) { unset ( $t hi s- >st or age[ spl _obj ect _hash( $obj ) ] ) ; } }

  • Or simply use Spl O

bj ect St or age Spl O bj ect St or age

slide-120
SLIDE 120

Marcus Börger Introduction to Object-oriented programming with PHP 120

cl ass M ySubj ect i m pl em ent s Subj ect { pr ot ect ed $obser ver s; publ i c f unct i on __const r uct ( ) { $t hi s- >obser ver = new O bj ect St or age; } publ i c f unct i on at t ach( O bser ver $o) { $t hi s- >obser ver s- >at t ach( $o) ; } publ i c f unct i on det ach( O bser ver $o) { $t hi s- >obser ver s- >det ach( $o) ; } publ i c f unct i on not i f y( ) { f or each( $t hi s- >obser ver s as $o) $o- >updat e( $t hi s) ; } } cl ass M yO bser ver i m pl em ent s O bser ver { publ i c f unct i on updat e( Subj ect $s) { / / do l oggi ng or som e ot her act i on } }

  • Concrete Examples: logging facilities: email,

debugging, SOAP message notifications.

Observer Pattern Implementation

slide-121
SLIDE 121

Marcus Börger Introduction to Object-oriented programming with PHP 121

At Last some Hints

  • List of all SPL classes

PHP 5.0.0

php –r ' pr i nt _r ( ar r ay_keys( spl _cl asses( ) ) ) ; '

  • Reflection of a built-in class

PHP 5.1.2

php - - r c <Cl ass>

  • Reflection of a function or method

PHP 5.1.2

php - - r f <Funct i on>

  • Reflection of a loaded extension

PHP 5.1.2

php - - r e <Ext ensi on>

  • Extension information/ configuration

PHP 5.2.2

php - - r i <Ext ensi on>

slide-122
SLIDE 122

Marcus Börger Introduction to Object-oriented programming with PHP 122

Reference

  • Everythining about PHP

http: / / php.net

  • These slides

http: / / talks.somabo.de

  • SPL Documentaion & Examples

http: / / php.net/ ~ helly/ php/ ext/ spl http: / / cvs.php.net/ php-src/ ext/ spl/ examples http: / / cvs.php.net/ php-src/ ext/ spl/ internal

  • George Schlossnagle

Advanced PHP Programming

  • Andi Gutmans, Stig Bakken, Derick Rethans

PHP 5 Power Programming