i ntroduction to object oriented program m ing w ith php
play

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


  1. 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 om 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( ) { / * . . . * / } } Marcus Börger Introduction to Object-oriented programming with PHP 23

  2. 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 om 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( ) { / * . . . * / } } Marcus Börger Introduction to Object-oriented programming with PHP 24

  3. PHP and OOP Marcus Börger Introduction to Object-oriented programming with PHP 25

  4. 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 Marcus Börger Introduction to Object-oriented programming with PHP 26

  5. 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 Marcus Börger Introduction to Object-oriented programming with PHP 27

  6. 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 Marcus Börger Introduction to Object-oriented programming with PHP 28

  7. PHP 5 OOP in detail Marcus Börger Introduction to Object-oriented programming with PHP 29

  8. 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 $ref $dup $obj = new O bj ect ( ) ; Instance 1 Instance 2 $r ef = $obj ; $dup = cl one cl one $obj ; Class Object Marcus Börger Introduction to Object-oriented programming with PHP 30

  9. 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 ) ; Marcus Börger Introduction to Object-oriented programming with PHP 31

  10. 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 ) ; Marcus Börger Introduction to Object-oriented programming with PHP 32

  11. 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 { $obj1 $obj2 var $pr op = " Hel l o\ n" ; } Instance 1 Instance 2 $prop $prop $obj 1 = new O bj ect ; $obj 1- >pr op = " Hel l o W or l d\ n" ; Class Object $obj 2 = new O bj ect ; $prop/default echo $obj 2- >pr op; / / Hel l o Marcus Börger Introduction to Object-oriented programming with PHP 33

  12. 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 $obj1 $obj2 cl ass O bj ect { Instance 1 Instance 2 var $pr op; $prop $prop 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 ; } Class Object } $stat O bj ect : : t est ( ) ; $obj 1 = new O bj ect ; $obj 2 = new O bj ect ; Marcus Börger Introduction to Object-oriented programming with PHP 34

  13. Pseudo constants � __CLASS__ __CLASS__ shows the current class name � __M __M ETHO ETHO D__ 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" ; } } Marcus Börger Introduction to Object-oriented programming with PHP 35

  14. 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; Derived pr ot ect ed $b; pr ot ect ed Base pr i vat e $c; pr i vat e $a } $b cl ass Der i ved ext ends Base { $c publ i c publ i c $a; publ i c publ i c $b; $a pr i vat e pr i vat e $c; $b } $c Base::$c Marcus Börger Introduction to Object-oriented programming with PHP 36

  15. 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 ( ) { } } Marcus Börger Introduction to Object-oriented programming with PHP 37

  16. 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" ; Marcus Börger Introduction to Object-oriented programming with PHP 38

  17. 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 or 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( ) ; Marcus Börger Introduction to Object-oriented programming with PHP 39

  18. 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" ; } } Marcus Börger Introduction to Object-oriented programming with PHP 40

  19. 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 { } Marcus Börger Introduction to Object-oriented programming with PHP 41

  20. Different Object same behavior � 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( ) { Line Ellipse f or each( $t hi s- >l i nes as $l i ne) $l i ne- >dr aw( ) ; } } $lines cl ass Rect angl e ext ends Pol ygon { } Circle Polygon 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( ) ; Rectangle } } Marcus Börger Introduction to Object-oriented programming with PHP 42

  21. 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( ) ; } Drawable 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( ) { Line Ellipse f or each( $t hi s- >l i nes as $l i ne) $l i ne- >dr aw( ) ; } } $lines cl ass Rect angl e ext ends Pol ygon { } Circle Polygon 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( ) ; Rectangle } } Marcus Börger Introduction to Object-oriented programming with PHP 43

  22. 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 Marcus Börger Introduction to Object-oriented programming with PHP 44

  23. 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 Marcus Börger Introduction to Object-oriented programming with PHP 45

  24. 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" ; } } Marcus Börger Introduction to Object-oriented programming with PHP 46

  25. 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 } } } Marcus Börger Introduction to Object-oriented programming with PHP 47

  26. 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 Tires Bicycle Vehicle Engine Car Bus Truck Diesel Gasoline Tank Turbine Plane Marcus Börger Introduction to Object-oriented programming with PHP 48

  27. 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 Marcus Börger Introduction to Object-oriented programming with PHP 49

  28. Dynam ic class loading Marcus Börger Introduction to Object-oriented programming with PHP 50

  29. Dynamic class loading � � __aut ol oad( ) is good __aut ol oad( ) is good when you're alone � 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 Marcus Börger Introduction to Object-oriented programming with PHP 51

  30. __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' ) ; } ?> Marcus Börger Introduction to Object-oriented programming with PHP 52

  31. 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' ) ; } ?> Marcus Börger Introduction to Object-oriented programming with PHP 53

  32. 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 Marcus Börger Introduction to Object-oriented programming with PHP 54

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

  34. 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 ( Except i on $e) { cat ch / / except i on handl i ng } ?> Marcus Börger Introduction to Object-oriented programming with PHP 56

  35. 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 } Marcus Börger Introduction to Object-oriented programming with PHP 57

  36. 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 } Marcus Börger Introduction to Object-oriented programming with PHP 58

  37. Practical use of exceptions � Constructor failure � Converting errors/ warnings to exceptions � Simplify error handling � Provide additional error information by tagging Marcus Börger Introduction to Object-oriented programming with PHP 59

  38. 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) ; } ?> Marcus Börger Introduction to Object-oriented programming with PHP 60

  39. 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" ; } ?> Marcus Börger Introduction to Object-oriented programming with PHP 61

  40. 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; } } } ?> Marcus Börger Introduction to Object-oriented programming with PHP 62

  41. 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' ) ; ?> Marcus Börger Introduction to Object-oriented programming with PHP 63

  42. 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 > Marcus Börger Introduction to Object-oriented programming with PHP 64

  43. 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 > Marcus Börger Introduction to Object-oriented programming with PHP 65

  44. SPL Exceptions � SPL provides a standard set of exceptions � Class Exception must be the root of all exceptions Marcus Börger Introduction to Object-oriented programming with PHP 66

  45. General distinguishing � Logi cExcept i on � Anything that could have been detected at compile time, during application design or 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 Marcus Börger Introduction to Object-oriented programming with PHP 67

  46. 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 Marcus Börger Introduction to Object-oriented programming with PHP 68

  47. 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 Marcus Börger Introduction to Object-oriented programming with PHP 69

  48. 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 ) { Compile-Time: $t hi s- >i t = $i t ; } Error in design 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) ; } } Marcus Börger Introduction to Object-oriented programming with PHP 70

  49. 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 { I nt er f ace I t er at or { f unct i on __const r uct ( I t er at or $i t ) f unct i on r ewi nd( ) ; { f unct i on val i d( ) ; $t hi s- >i t = $i t ; f unct i on cur r ent ( ) ; } f unct i on __cal l ( $f unc, $ar gs) f unct i on key( ) ; { f unct i on next ( ) ; $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) ; } } Marcus Börger Introduction to Object-oriented programming with PHP 71

  50. 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 { I nt er f ace I t er at or { f unct i on __const r uct ( I t er at or $i t ) f unct i on r ewi nd( ) ; { f unct i on val i d( ) ; $t hi s- >i t = $i t ; f unct i on cur r ent ( ) ; } f unct i on __cal l ( $f unc, $ar gs) f unct i on key( ) ; { f unct i on next ( ) ; $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 ( ) ; } } Marcus Börger Introduction to Object-oriented programming with PHP 72

  51. Expecting formatted data � Opening a file for reading Run-Time: File might not be accessible or exist $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( ) ; Marcus Börger Introduction to Object-oriented programming with PHP 73

  52. Expecting formatted data � Reading a formatted file line by line Run-Time: File might not be accessible or exist $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 ( ) ; Run-Time: } data is different for $dat a[ ] = $l ; every execution } � ! 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 Marcus Börger Introduction to Object-oriented programming with PHP 74

  53. Expecting formatted data � Cehcking data after pre-processing Run-Time: Filemight not be accessible or exist $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( ) ; Run-Time: } data is different for $dat a[ ] = $l ; every execution } / / 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( ) ; Marcus Börger Introduction to Object-oriented programming with PHP 75

  54. Expecting formatted data � Processing pre-checked data Run-Time: File might not be accessible or exist $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( ) ; Run-Time: } data is different for $dat a[ ] = $l ; every execution } i f ( count ( $dat a) < 10) t hr ow new Under f l owExcept i on( ) ; / / m aybe m or e pr ecessi ng code f or each( $dat a as &$v) { Compile-Time: i f ( count ( $v) == 2) { exception signals t hr ow new Dom ai nExcept i on( ) ; failed precondition } $v = $v[ 0] * $v[ 1] ; } Marcus Börger Introduction to Object-oriented programming with PHP 76

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

  56. 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' ) ; Marcus Börger Introduction to Object-oriented programming with PHP 78

  57. 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) ) ; Marcus Börger Introduction to Object-oriented programming with PHP 79

  58. Built-in I nterfaces Marcus Börger Introduction to Object-oriented programming with PHP 80

  59. 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 Marcus Börger Introduction to Object-oriented programming with PHP 81

  60. 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 ) ; } Marcus Börger Introduction to Object-oriented programming with PHP 82

  61. 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 ) { / * . . . * / } } Marcus Börger Introduction to Object-oriented programming with PHP 83

  62. ArrayAccess Example � We want to create variables which can be shared between processes. � We will set up interception so that access attempts on the variable are actually performed through a DBM file. Marcus Börger Introduction to Object-oriented programming with PHP 84

  63. 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) ; } } ?> Marcus Börger Introduction to Object-oriented programming with PHP 85

  64. 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 ' ] ) ; ?> Marcus Börger Introduction to Object-oriented programming with PHP 86

  65. 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 or l d\ n" ; } f or each( new O bj ect as $pr op) { echo $pr op; } ?> Marcus Börger Introduction to Object-oriented programming with PHP 87

  66. What are Iterators � Iterators are a concept to iterate anything that contains other things. � Iterators allow to encapsulate algorithms Marcus Börger Introduction to Object-oriented programming with PHP 88

  67. 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 Marcus Börger Introduction to Object-oriented programming with PHP 89

  68. 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 , . . . Marcus Börger Introduction to Object-oriented programming with PHP 90

  69. 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 () Marcus Börger Introduction to Object-oriented programming with PHP 91

  70. The big difference � Arrays � require memory for all elements � allow to access any element directly � I terators � only know one element at a time � only 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 Marcus Börger Introduction to Object-oriented programming with PHP 92

  71. 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 Marcus Börger Introduction to Object-oriented programming with PHP 93

  72. 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 Traversable Iterator IteratorAggregate + rewind () : void + valid () : boolean + current () : mixed + getIterator () : Iterator + key () : mixed + next () : void Marcus Börger Introduction to Object-oriented programming with PHP 94

  73. Implementing Iterators Traversable Iterator IteratorAggregate + rewind () : void + valid () : boolean + getIterator () : Iterator + current () : mixed + key () : mixed + next () : void IteratorImpl AggregateImpl + <<Implement>> rewind () : void + <<Implement>> valid () : boolean + <<Implement>> getIterator () : Iterator + <<Implement>> current () : mixed + <<Implement>> key () : mixed + <<Implement>> next () : void Marcus Börger Introduction to Object-oriented programming with PHP 95

  74. 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 } ?> Marcus Börger Introduction to Object-oriented programming with PHP 96

  75. How Iterators work � Internal Iterators � User Iterators < ?php interface Iterator { function rewind(); function valid(); function current(); function key(); function next(); } ?> < ?php $it = get_resource(); for ($it-> rewind(); $it-> valid(); $it-> next()) { $value = $it-> current(); $key = $it-> key(); } ?> Marcus Börger Introduction to Object-oriented programming with PHP 97

  76. How Iterators work � Internal Iterators � User Iterators < ?php interface Iterator { function rewind(); function valid(); < ?php function current(); $it = get_resource(); function key(); foreach($it as $key= > $val) { function next(); / / access data } } ?> ?> Marcus Börger Introduction to Object-oriented programming with PHP 98

  77. How Iterators work � Internal Iterators � User Iterators < ?php class FilterIterator implements Iterator { < ?php function __construct(Iterator $input)... interface Iterator { function rewind()... function rewind(); function accept()... function valid(); function valid()... function current(); function current()... function key(); function key()... function next(); function next()... } } ?> ?> < ?php $it = get_resource(); foreach(new Filter($it, $filter_param) as $key= > $val) { / / access filtered data only } ?> Marcus Börger Introduction to Object-oriented programming with PHP 99

  78. Debug Session <?php <?php PHP 5.1 cl ass Ar r ayI t er at or { $a = ar r ay( 1, 2, 3) ; pr ot ect ed $ar ; $o = new Ar r ayI t er at or ( $a) ; f unct i on __const r uct ( Ar r ay $ar ) { f or each( $o as $key => $val ) { $t hi s- >ar = $ar ; echo " $key => $va\ n" ; } } f unct i on r ewi nd( ) { ?> r ewi nd( $t hi s- >ar ) ; } f ucnt i on val i d( ) { 0 => 1 r et ur n ! i s_nul l ( key( $t hi s- >ar ) ) ; 1 => 2 } 2 => 3 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 ) ; } } ?> Marcus Börger Introduction to Object-oriented programming with PHP 100

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend