Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
PROXY PATTERN   IN PHP
MARCO PIVETTADoctrine core teamZf2 contributorWasting time on:  OcraDiCompiler  OcraServiceManager  OcraCachedViewResolver...
WHAT IS A PROXY?A proxy is generally an object whoseinterface is a layer between us and a   different object with the same...
Simplified, in PHP Even if were not implementing an    interface, the interface ofC s o e P o yis the same as the utmrrx  ...
WHERE TO USE PROXIES?As of the LSP , a proxy can be used inany place where the "proxied" object            can be used.
WHEN TO USE A PROXY?Lazy loadingRemote objectsSmart reference/Weak referenceProtectionAOPNull object fallback
LAZY LOADING We may want to use lazy loading toavoid IO operations or heavy loading   operation until really needed
LAZY LOADING PATTERNS    1. Virtual Object    2. Value Holder    3. Ghost Object
VIRTUAL OBJECTAn object whose properties are all setto n l , and where each access to the    ul        properties is track...
VALUE HOLDER An object that can hold an instance ofthe original proxied object, and loads it          only when needed.
GHOST OBJECT  An object whose properties are the same of the proxied object, but n l .                                  ul...
VALUE HOLDER EXAMPLE        (1/3)casIae{ls mg  pbi fnto _cntut$ah {   ulc ucin _osrc(pt)     $hs>mg =iaeraermpg$      ti-i...
VALUE HOLDER EXAMPLE        (2/3)casIaerx etnsIae{ls mgPoy xed mg  poetd$mg;   rtce iae  pbi fnto _cntut$ah {   ulc ucin _...
VALUE HOLDER EXAMPLE        (3/3)$m1=nwIaerx(/aht/mg1jg) ig  e mgPoypt/oiae.p;vrdm(eoygtuae);/ ~0K a_upmmr_e_sg() / 20b$m2...
LAZY LOADING PROS/CONSAdvantages  Low memory impact  Low overhead  Easy to implement  Useful to determine object "dirty"  ...
REMOTE OBJECTIt basically is a specific form of lazy                loading
REMOTE OBJECT EXAMPLE        (1/3)casTet{ls we  poetd$aa  rtce dt;    pbi fnto _cntutary$aa    ulc ucin _osrc(ra dt){     ...
REMOTE OBJECT EXAMPLE        (2/3)casTetrx etnsTet{ls wePoy xed we  poetd$p;poetd$we;poe  rtce ai rtce tet rtctd$de i;   p...
REMOTE OBJECT EXAMPLE        (3/3)$we =nwTetaryet = rxe itet   e we(ra(tx > PoisnPP)  H!);vrdm(tet>eTx() / rxe i Pa_up$we-...
REMOTE OBJECT PROS/CONSAdvantages  Abstraction of a remote object  You can re-define the proxied  objects API locallyDis-a...
SMART REFERENCE  Smart reference can be used to:swap the proxied object at runtimereference singletons or use internalstat...
SMART REFERENCE WITH      WEAKREFUsing Weakref to save memory on     long-running processescasIaerx etnsIae{ls mgPoy xed m...
SMART REFERENCE WITH A       REGISTRYcasIaerx etnsIae{ls mgPoy xed mg  / [.](e peiu eape   / .. se rvos xml)  piaefnto ii(...
SMART REFERENCE       PROS/CONSMainly memory usage, but it depends  on how you setup your "smart"           reference
PROTECTION PROXYProtection proxy comes into play whenyou want to transparently limit access    to an API through a set of ...
PROTECTION PROXY (1/2)casRmtAirx etnsRmtAi{ls eoepPoy xed eoep  poetd$on =0   rtce cut   ;  pbi fnto _cntutRmtAi$   ulc uc...
PROTECTION PROXY (2/2)$p =nwRmtAirx(e RmtAi/ .ai   e eoepPoynw eoep(* ..*) 5)  /, 0;wie(){ hl 1   $p-dSuf) / RmtAiii ecp  ...
PROTECTION PROXY       PROS/CONSAdvantages  Transparent filtering or limiting of  access to an objectDis-advantages  Modif...
NULL OBJECT FALLBACK          PROXY    A null object is an object thatimplements an interface, but produces  no side effec...
NULL OBJECT FALLBACK       PROXY EXAMPLEcasCsoePoyetnsCsoe { ls utmrrx xed utmr   pbi fnto _cntutD $b $d   ulc ucin _osrc(...
NULL OBJECT FALLBACK      PROXY PROSPerformance (with small # ofinstances)Reduced NPaths, therefore code iseasier to test
AOP AND PROXIESProxies basically enable us to have logic  between us and any object, making  AOP easy even when the langua...
AOP EXAMPLES/* * *@Oah(t=60    APCcetl30) */pbi fnto dHaytf( { ulc ucin oevSuf)    / [.]     / ..}          Becomes:pbi fn...
IMPLEMENTATION DETAILS IN          PHP
IMPLEMENTING THE PUBLIC           API1. The Proxy class MUST extend the   proxied class2. Each of the proxied methods must...
PUBLIC PROPERTIES        PROXYINGcasCsoe { ls utmr   pbi $ae   ulc nm;   pbi $unm;   ulc srae}casCsoePoyetnsCsoe {ls utmrr...
A COMPLETE GHOST OBJECT    IMPLEMENTATIONhttps://gist.github.com/4038004
SOME USEFUL LIBRARIEShttp://flow.typo3.orghttps://github.com/schmittjoh/cg-libraryhttps://github.com/doctrine/commonhttps:...
CODE GENERATIONSee Doctrines Proxy Generator
QUESTIONS?
Proxy OOP Pattern in PHP
Upcoming SlideShare
Loading in …5
×

Proxy OOP Pattern in PHP

7,698 views

Published on

An introduction of the Proxy Pattern for PHP Developers.

Covers topics such as Lazy loading, Weak References, Smart References, Protection and Remote proxies.

Published in: Technology
  • DOWNLOAD THE BOOK INTO AVAILABLE FORMAT (New Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://urlzs.com/UABbn } ......................................................................................................................... Download Full EPUB Ebook here { https://urlzs.com/UABbn } ......................................................................................................................... Download Full doc Ebook here { https://urlzs.com/UABbn } ......................................................................................................................... Download PDF EBOOK here { https://urlzs.com/UABbn } ......................................................................................................................... Download EPUB Ebook here { https://urlzs.com/UABbn } ......................................................................................................................... Download doc Ebook here { https://urlzs.com/UABbn } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book THE can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer THE is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBOOK .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, CookBOOK, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, EBOOK, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story THE Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money THE the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths THE Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Follow the link, new dating source: ❤❤❤ http://bit.ly/39pMlLF ❤❤❤
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Sex in your area is here: ♥♥♥ http://bit.ly/39pMlLF ♥♥♥
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here

Proxy OOP Pattern in PHP

  1. 1. PROXY PATTERN IN PHP
  2. 2. MARCO PIVETTADoctrine core teamZf2 contributorWasting time on: OcraDiCompiler OcraServiceManager OcraCachedViewResolver Doctrine ZF2 Modules ZeffMu AssetManager KJSencha Follow @Ocramius Follow @Ocramius
  3. 3. WHAT IS A PROXY?A proxy is generally an object whoseinterface is a layer between us and a different object with the same interface.
  4. 4. Simplified, in PHP Even if were not implementing an interface, the interface ofC s o e P o yis the same as the utmrrx one of C s o e utmr
  5. 5. WHERE TO USE PROXIES?As of the LSP , a proxy can be used inany place where the "proxied" object can be used.
  6. 6. WHEN TO USE A PROXY?Lazy loadingRemote objectsSmart reference/Weak referenceProtectionAOPNull object fallback
  7. 7. LAZY LOADING We may want to use lazy loading toavoid IO operations or heavy loading operation until really needed
  8. 8. LAZY LOADING PATTERNS 1. Virtual Object 2. Value Holder 3. Ghost Object
  9. 9. VIRTUAL OBJECTAn object whose properties are all setto n l , and where each access to the ul properties is tracked. Access triggers lazy loading on the property.
  10. 10. VALUE HOLDER An object that can hold an instance ofthe original proxied object, and loads it only when needed.
  11. 11. GHOST OBJECT An object whose properties are the same of the proxied object, but n l . ulAccessing any method causes loading of the properties. Doctrine Proxies are generated this way.
  12. 12. VALUE HOLDER EXAMPLE (1/3)casIae{ls mg pbi fnto _cntut$ah { ulc ucin _osrc(pt) $hs>mg =iaeraermpg$ ti-iae mgcetfoje(pah;t) } pbi fnto gtie){ ulc ucin eSz( rtr aryiaex$hs>mg) i eun ra(mgs(ti-iae,mgs(ti-iae) aey$hs>mg); }}
  13. 13. VALUE HOLDER EXAMPLE (2/3)casIaerx etnsIae{ls mgPoy xed mg poetd$mg; rtce iae pbi fnto _cntut$ah { ulc ucin _osrc(pt) $hs>ah=$ah ti-pt pt; } piaefnto ii( { rvt ucin nt) i (!$hs>mg){ f ti-iae $hs>mg =nwIae$hs> ti-iae e mg(ti-pt)ah; } } pbi fnto gtie){ ulc ucin eSz( $hs>nt) ti-ii(; rtr $hs>mg-gtie) eun ti-iae>eSz(; }}
  14. 14. VALUE HOLDER EXAMPLE (3/3)$m1=nwIaerx(/aht/mg1jg) ig e mgPoypt/oiae.p;vrdm(eoygtuae);/ ~0K a_upmmr_e_sg() / 20b$m2=nwIaerx(/aht/mg2jg) ig e mgPoypt/oiae.p;vrdm(eoygtuae);/ ~0K a_upmmr_e_sg() / 20b$m3=nwIaerx(/aht/mg3jg) ig e mgPoypt/oiae.p;vrdm(eoygtuae);/ ~0K a_upmmr_e_sg() / 20b$ie =$m1>eSz(;sz1 ig-gtie)vrdm(eoygtuae);/ ~Ma_upmmr_e_sg() / 4b$ie =$m2>eSz(;sz2 ig-gtie)vrdm(eoygtuae);/ ~Ma_upmmr_e_sg() / 8b
  15. 15. LAZY LOADING PROS/CONSAdvantages Low memory impact Low overhead Easy to implement Useful to determine object "dirty" statusDis-advantages Not optimal for data that is always loaded Lazy loading means lazy failing
  16. 16. REMOTE OBJECTIt basically is a specific form of lazy loading
  17. 17. REMOTE OBJECT EXAMPLE (1/3)casTet{ls we poetd$aa rtce dt; pbi fnto _cntutary$aa ulc ucin _osrc(ra dt){ $hs>aa=$aa ti-dt dt; } pbi fnto gtet){ ulc ucin eTx( rtr $hs>aaet] eun ti-dt[tx; }}
  18. 18. REMOTE OBJECT EXAMPLE (2/3)casTetrx etnsTet{ls wePoy xed we poetd$p;poetd$we;poe rtce ai rtce tet rtctd$de i; pbi fnto _cntutTitrp $ ulc ucin _osrc(wteAiai $d { p, i) $hs>p =$p;$hs>d=$d ti-ai ai ti-i i; } piaefnto ii( { rvt ucin nt) i (!$hs>we){ f ti-tet $hs>we =nwTet$hs> ti-tet e we(ti-ai>e(ti-i); p-gt$hs>d) } } pbi fnto gtet){ ulc ucin eTx( $hs>nt) ti-ii(; rtr $hs>we-gtet) eun ti-tet>eTx(; }}
  19. 19. REMOTE OBJECT EXAMPLE (3/3)$we =nwTetaryet = rxe itet e we(ra(tx > PoisnPP) H!);vrdm(tet>eTx() / rxe i Pa_up$we-gtet); / Pois nH!P$p =nwTitrp(*yda*) / z,bai e wteAi/ ad /; / f uz,ecz t$eoewe =nwTetrx(ai 20478rmtTet e wePoy$p, 863098850;6366)vrdm(rmtTet>eTx() / wea_up$eoewe-gtet); / Tettx!et$eoewe =nwTetrx(ai 20478rmtTet e wePoy$p, 863098851;6366)vrdm(rmtTet>eTx() / ntea_up$eoewe-gtet); / Aohrtx! et
  20. 20. REMOTE OBJECT PROS/CONSAdvantages Abstraction of a remote object You can re-define the proxied objects API locallyDis-advantages To use such a proxy, you almost always need a configured remote client Remote objects fail very easily
  21. 21. SMART REFERENCE Smart reference can be used to:swap the proxied object at runtimereference singletons or use internalstatic registriesOptimize memory usage
  22. 22. SMART REFERENCE WITH WEAKREFUsing Weakref to save memory on long-running processescasIaerx etnsIae{ls mgPoy xed mg / [.](e peiu eape / .. se rvos xml) piaefnto ii( { rvt ucin nt) i (!$hs>mgRf| !$hs>m f ti-iaee | ti-iaee-vld) {gRf>ai() $hs>mgRf=nwWaRfnw ti-iaee e eke(eIae$hs>ah) mg(ti-pt); } rtr $hs>mgRf>e(; eun ti-iaee-gt) } pbi fnto gtie){ ulc ucin eSz( rtr $hs>nt)>eSz(; eun ti-ii(-gtie) }}
  23. 23. SMART REFERENCE WITH A REGISTRYcasIaerx etnsIae{ls mgPoy xed mg / [.](e peiu eape / .. se rvos xml) piaefnto ii( { rvt ucin nt) i (ul==$hs>mg){ f nl = ti-iae $hs>mg =Iaeeity:e ti-iae mgRgsr:gt(ti-pt)$hs>ah; } } pbi fnto gtie){ ulc ucin eSz( $hs>nt) ti-ii(; rtr $hs>mg-gtie) eun ti-iae>eSz(; }}
  24. 24. SMART REFERENCE PROS/CONSMainly memory usage, but it depends on how you setup your "smart" reference
  25. 25. PROTECTION PROXYProtection proxy comes into play whenyou want to transparently limit access to an API through a set of rules (ACL/limits)
  26. 26. PROTECTION PROXY (1/2)casRmtAirx etnsRmtAi{ls eoepPoy xed eoep poetd$on =0 rtce cut ; pbi fnto _cntutRmtAi$ ulc ucin _osrc(eoep ap,$ii){i lmt $hs>p =$p;$hs>ii =$ ti-ai ai ti-lmt lii;mt } piaefnto cut){ rvt ucin on( i (+ti-cut>$hs>ii){ f +$hs>on ti-lmt trwnwRmtAiii(SAP ho e eoepLmtTH!;) } } pbi fnto dSuf){ ulc ucin otf( $hs>on(; ti-cut) rtr $hs>p-dSuf) eun ti-ai>otf(; }}
  27. 27. PROTECTION PROXY (2/2)$p =nwRmtAirx(e RmtAi/ .ai e eoepPoynw eoep(* ..*) 5) /, 0;wie(){ hl 1 $p-dSuf) / RmtAiii ecp ai>otf(; / eoepLmt xetin o!}
  28. 28. PROTECTION PROXY PROS/CONSAdvantages Transparent filtering or limiting of access to an objectDis-advantages Modifies proxied object behavior! More like a decorator!
  29. 29. NULL OBJECT FALLBACK PROXY A null object is an object thatimplements an interface, but produces no side effects. It replaces n l . ul Using null objects allows us to workwith the assumption that an object will always be available, reducing checks against n l by a lot. ul
  30. 30. NULL OBJECT FALLBACK PROXY EXAMPLEcasCsoePoyetnsCsoe { ls utmrrx xed utmr pbi fnto _cntutD $b $d ulc ucin _osrc(b d, i){ $hs>utmr=$b>id$d; ti-csoe d-fn(i) i (!$hs>utmr { f ti-csoe) $hs>utmr=nwNlCsoe ti-csoe e ulutmr)(; } } pbi fnto dSuf){ ulc ucin otf( rtr $hs>utmr>otf(; eun ti-csoe-dSuf) }}
  31. 31. NULL OBJECT FALLBACK PROXY PROSPerformance (with small # ofinstances)Reduced NPaths, therefore code iseasier to test
  32. 32. AOP AND PROXIESProxies basically enable us to have logic between us and any object, making AOP easy even when the language doesnt allow it. We can use code generation to createon-the-fly proxies with our custom AOP logic executed pre- and post- any method of the proxied object.
  33. 33. AOP EXAMPLES/* * *@Oah(t=60 APCcetl30) */pbi fnto dHaytf( { ulc ucin oevSuf) / [.] / ..} Becomes:pbi fnto dHaytf( {ulc ucin oevSuf) i(cce =$hs>ah-gtoevS f$ahd ti-cce>e(dHaytuf,fn_e_rs)){f ucgtag() rtr $ahd eun cce; } $eun=$hs>rgnlbet>oevS rtr ti-oiiaOjc-dHaytf(;uf) $hs>ah-st$eun oevSuf ti-cce>e(rtr, dHaytf,fn_e_rs); ucgtag() rtr $eun eun rtr;}
  34. 34. IMPLEMENTATION DETAILS IN PHP
  35. 35. IMPLEMENTING THE PUBLIC API1. The Proxy class MUST extend the proxied class2. Each of the proxied methods must be rewritten3. Proxies should be serializable4. Proxies should handle public properties
  36. 36. PUBLIC PROPERTIES PROXYINGcasCsoe { ls utmr pbi $ae ulc nm; pbi $unm; ulc srae}casCsoePoyetnsCsoe {ls utmrrx xed utmr pbi fnto _cntutCsoe $u ulc ucin _osrc(utmr cstmr {oe) ust$hs>ae $hs>unm) ne(ti-nm, ti-srae; $hs>utmr=$utmr ti-csoe csoe; } pbi fnto _st$ae $au){ ulc ucin _e(nm, vle $hs>utmr>nm =$au; ti-csoe-$ae vle } pbi fnto _gt$ae { ulc ucin _e(nm) rtr $hs>utmr>nm; eun ti-csoe-$ae } / _ist _ust / _se, _ne}
  37. 37. A COMPLETE GHOST OBJECT IMPLEMENTATIONhttps://gist.github.com/4038004
  38. 38. SOME USEFUL LIBRARIEShttp://flow.typo3.orghttps://github.com/schmittjoh/cg-libraryhttps://github.com/doctrine/commonhttps://github.com/lisachenko/go-aop-php
  39. 39. CODE GENERATIONSee Doctrines Proxy Generator
  40. 40. QUESTIONS?

×