SlideShare une entreprise Scribd logo
1  sur  41
Télécharger pour lire hors ligne
PROXY PATTERN
   IN PHP
MARCO PIVETTA
Doctrine core team
Zf2 contributor
Wasting time on:
  OcraDiCompiler
  OcraServiceManager
  OcraCachedViewResolver
  Doctrine ZF2 Modules
  ZeffMu
  AssetManager
  KJSencha
  Follow @Ocramius
                     Follow @Ocramius
WHAT IS A PROXY?
A proxy is generally an object whose
interface is a layer between us and a
   different object with the same
               interface.
Simplified, in PHP



 Even if we're not implementing an
    interface, the interface of
C s o e P o yis the same as the
 utmrrx
         one of C s o e
                 utmr
WHERE TO USE PROXIES?
As of the LSP , a proxy can be used in
any place where the "proxied" object
            can be used.
WHEN TO USE A PROXY?
Lazy loading
Remote objects
Smart reference/Weak reference
Protection
AOP
Null object fallback
LAZY LOADING
 We may want to use lazy loading to
avoid IO operations or heavy loading
   operation until really needed
LAZY LOADING PATTERNS
    1. Virtual Object
    2. Value Holder
    3. Ghost Object
VIRTUAL OBJECT
An object whose properties are all set
to n l , and where each access to the
    ul
        properties is tracked.
  Access triggers lazy loading on the
              property.
VALUE HOLDER
 An object that can hold an instance of
the 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
Accessing any method causes loading of
            the properties.
 Doctrine Proxies are generated this
                 way.
VALUE HOLDER EXAMPLE
        (1/3)
casIae{
ls mg
  pbi fnto _cntut$ah {
   ulc ucin _osrc(pt)
     $hs>mg =iaeraermpg$
      ti-iae mgcetfoje(p
ah;
t)
  }

   pbi fnto gtie){
    ulc ucin eSz(
      rtr aryiaex$hs>mg) i
       eun ra(mgs(ti-iae,
mgs(ti-iae)
 aey$hs>mg);
   }
}
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(;
    }
}
VALUE HOLDER EXAMPLE
        (3/3)
$m1=nwIaerx(/aht/mg1jg)
 ig  e mgPoy'pt/oiae.p'
;
vrdm(eoygtuae);/ ~0K
 a_upmmr_e_sg() / 20b
$m2=nwIaerx(/aht/mg2jg)
 ig  e mgPoy'pt/oiae.p'
;
vrdm(eoygtuae);/ ~0K
 a_upmmr_e_sg() / 20b
$m3=nwIaerx(/aht/mg3jg)
 ig  e mgPoy'pt/oiae.p'
;
vrdm(eoygtuae);/ ~0K
 a_upmmr_e_sg() / 20b

$ie =$m1>eSz(;
sz1  ig-gtie)
vrdm(eoygtuae);/ ~M
a_upmmr_e_sg() / 4b
$ie =$m2>eSz(;
sz2  ig-gtie)
vrdm(eoygtuae);/ ~M
a_upmmr_e_sg() / 8b
LAZY LOADING PROS/CONS
Advantages
  Low memory impact
  Low overhead
  Easy to implement
  Useful to determine object "dirty"
  status
Dis-advantages
  Not optimal for data that is always
  loaded
  Lazy loading means lazy failing
REMOTE OBJECT
It 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)
{
        $hs>aa=$aa
         ti-dt  dt;
    }

    pbi fnto gtet){
     ulc ucin eTx(
       rtr $hs>aa'et]
        eun ti-dt[tx';
    }
}
REMOTE OBJECT EXAMPLE
        (2/3)
casTetrx etnsTet{
ls wePoy xed we
  poetd$p;poetd$we;poe
  rtce ai rtce tet rtc
td$d
e i;

   pbi fnto _cntutTitrp $
    ulc ucin _osrc(wteAi
ai $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(;
   }
}
REMOTE OBJECT EXAMPLE
        (3/3)
$we =nwTetary'et = 'rxe i
tet   e we(ra(tx' > Pois
nPP')
  H!);
vrdm(tet>eTx() / 'rxe i P
a_up$we-gtet); / Pois n
H!
P'

$p =nwTitrp(*yda*) / z,b
ai   e wteAi/ ad /; / f u
z,ec
z t

$eoewe =nwTetrx(ai 20478
rmtTet   e wePoy$p, 8630
98850;
6366)
vrdm(rmtTet>eTx() / 'we
a_up$eoewe-gtet); / Tet
tx!
et'
$eoewe =nwTetrx(ai 20478
rmtTet   e wePoy$p, 8630
98851;
6366)
vrdm(rmtTet>eTx() / 'nte
a_up$eoewe-gtet); / Aoh
rtx!
  et'
REMOTE OBJECT PROS/CONS
Advantages
  Abstraction of a remote object
  You can re-define the proxied
  object's API locally
Dis-advantages
  To use such a proxy, you almost
  always need a configured remote
  client
  Remote objects fail very easily
SMART REFERENCE
  Smart reference can be used to:
swap the proxied object at runtime
reference singletons or use internal
static registries
Optimize memory usage
SMART REFERENCE WITH
      WEAKREF
Using Weakref to save memory on
     long-running processes
casIaerx 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-i
aee-vld) {
gRf>ai()
        $hs>mgRf=nwWaRfnw
         ti-iaee   e eke(e
Iae$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)
    }
}
SMART REFERENCE WITH A
       REGISTRY
casIaerx 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(;
    }
}
SMART REFERENCE
       PROS/CONS
Mainly memory usage, but it depends
  on how you setup your "smart"
           reference
PROTECTION PROXY
Protection proxy comes into play when
you want to transparently limit access
    to an API through a set of rules
             (ACL/limits)
PROTECTION PROXY (1/2)
casRmtAirx etnsRmtAi{
ls eoepPoy xed eoep
  poetd$on =0
   rtce cut   ;
  pbi fnto _cntutRmtAi$
   ulc ucin _osrc(eoep a
p,$ii){
i lmt
     $hs>p =$p;$hs>ii =$
      ti-ai  ai ti-lmt  l
ii;
mt
  }

     piaefnto cut){
     rvt ucin on(
       i (+ti-cut>$hs>ii){
        f +$hs>on   ti-lmt
          trwnwRmtAiii(SAP
           ho e eoepLmt'TH!
';
)
         }
     }

     pbi fnto dSuf){
      ulc ucin otf(
        $hs>on(;
         ti-cut)
        rtr $hs>p-dSuf)
         eun ti-ai>otf(;
     }
}
PROTECTION PROXY (2/2)
$p =nwRmtAirx(e RmtAi/ .
ai   e eoepPoynw eoep(* .
.*) 5)
  /, 0;

wie(){
 hl 1
   $p-dSuf) / RmtAiii ecp
    ai>otf(; / eoepLmt xet
in
 o!
}
PROTECTION PROXY
       PROS/CONS
Advantages
  Transparent filtering or limiting of
  access to an object
Dis-advantages
  Modifies proxied object behavior!
  More like a decorator!
NULL OBJECT FALLBACK
          PROXY
    A null object is an object that
implements an interface, but produces
  no side effects. It replaces n l .
                                ul
 Using null objects allows us to work
with the assumption that an object will
 always be available, reducing checks
         against n l by a lot.
                  ul
NULL OBJECT FALLBACK
       PROXY EXAMPLE
casCsoePoyetnsCsoe {
 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 ulutm
r)
(;
        }
    }

    pbi fnto dSuf){
     ulc ucin otf(
       rtr $hs>utmr>otf(;
        eun ti-csoe-dSuf)
    }
}
NULL OBJECT FALLBACK
      PROXY PROS
Performance (with small # of
instances)
Reduced NPaths, therefore code is
easier to test
AOP AND PROXIES
Proxies basically enable us to have logic
  between us and any object, making
  AOP easy even when the language
            doesn't allow it.
 We can use code generation to create
on-the-fly proxies with our custom AOP
   logic executed pre- and post- any
     method of the proxied object.
AOP EXAMPLES
/*
 *
 *@Oah(t=60
    APCcetl30)
 */
pbi fnto dHaytf( {
 ulc ucin oevSuf)
    / [.]
     / ..
}


          Becomes:
pbi fnto dHaytf( {
ulc ucin oevSuf)
  i(cce =$hs>ah-gt'oevS
   f$ahd   ti-cce>e(dHayt
uf,fn_e_rs)){
f' ucgtag()
     rtr $ahd
      eun cce;
  }

   $eun=$hs>rgnlbet>oevS
   rtr  ti-oiiaOjc-dHay
tf(;
uf)
   $hs>ah-st$eun 'oevSuf
   ti-cce>e(rtr, dHaytf'
,fn_e_rs);
  ucgtag()

    rtr $eun
    eun rtr;
}
IMPLEMENTATION DETAILS IN
          PHP
IMPLEMENTING THE PUBLIC
           API
1. The Proxy class MUST extend the
   proxied class
2. Each of the proxied methods must be
   rewritten
3. Proxies should be serializable
4. Proxies should handle public
   properties
PUBLIC PROPERTIES
        PROXYING
casCsoe {
 ls utmr
   pbi $ae
   ulc nm;
   pbi $unm;
   ulc srae
}

casCsoePoyetnsCsoe {
ls utmrrx xed utmr
  pbi fnto _cntutCsoe $u
   ulc ucin _osrc(utmr cs
tmr {
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
}
A COMPLETE GHOST OBJECT
    IMPLEMENTATION
https://gist.github.com/4038004
SOME USEFUL LIBRARIES
http://flow.typo3.org
https://github.com/schmittjoh/cg-
library
https://github.com/doctrine/common
https://github.com/lisachenko/go-
aop-php
CODE GENERATION
See Doctrine's Proxy Generator
QUESTIONS?

Contenu connexe

Tendances

Debugging: Rules & Tools
Debugging: Rules & ToolsDebugging: Rules & Tools
Debugging: Rules & ToolsIan Barber
 
Process monitoring in UNIX shell scripting
Process monitoring in UNIX shell scriptingProcess monitoring in UNIX shell scripting
Process monitoring in UNIX shell scriptingDan Morrill
 
2013-02-21 - .NET UG Rhein-Neckar: JavaScript Best Practices
2013-02-21 - .NET UG Rhein-Neckar: JavaScript Best Practices2013-02-21 - .NET UG Rhein-Neckar: JavaScript Best Practices
2013-02-21 - .NET UG Rhein-Neckar: JavaScript Best PracticesJohannes Hoppe
 
Android audio system(audio_hardwareinterace)
Android audio system(audio_hardwareinterace)Android audio system(audio_hardwareinterace)
Android audio system(audio_hardwareinterace)fefe7270
 
Groovy on the Shell
Groovy on the ShellGroovy on the Shell
Groovy on the Shellsascha_klein
 
The Browser Environment - A Systems Programmer's Perspective
The Browser Environment - A Systems Programmer's PerspectiveThe Browser Environment - A Systems Programmer's Perspective
The Browser Environment - A Systems Programmer's PerspectiveEleanor McHugh
 
Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02nikomatsakis
 
C++の話(本当にあった怖い話)
C++の話(本当にあった怖い話)C++の話(本当にあった怖い話)
C++の話(本当にあった怖い話)Yuki Tamura
 
Php7 hashtable
Php7 hashtablePhp7 hashtable
Php7 hashtable桐 王
 
ZeroMQ: Messaging Made Simple
ZeroMQ: Messaging Made SimpleZeroMQ: Messaging Made Simple
ZeroMQ: Messaging Made SimpleIan Barber
 
Créer une base NoSQL en 1 heure
Créer une base NoSQL en 1 heureCréer une base NoSQL en 1 heure
Créer une base NoSQL en 1 heureAmaury Bouchard
 

Tendances (20)

Vcs28
Vcs28Vcs28
Vcs28
 
Five
FiveFive
Five
 
Debugging: Rules & Tools
Debugging: Rules & ToolsDebugging: Rules & Tools
Debugging: Rules & Tools
 
Php&redis presentation
Php&redis presentationPhp&redis presentation
Php&redis presentation
 
Sbaw091006
Sbaw091006Sbaw091006
Sbaw091006
 
Process monitoring in UNIX shell scripting
Process monitoring in UNIX shell scriptingProcess monitoring in UNIX shell scripting
Process monitoring in UNIX shell scripting
 
2013-02-21 - .NET UG Rhein-Neckar: JavaScript Best Practices
2013-02-21 - .NET UG Rhein-Neckar: JavaScript Best Practices2013-02-21 - .NET UG Rhein-Neckar: JavaScript Best Practices
2013-02-21 - .NET UG Rhein-Neckar: JavaScript Best Practices
 
C99[2]
C99[2]C99[2]
C99[2]
 
Android audio system(audio_hardwareinterace)
Android audio system(audio_hardwareinterace)Android audio system(audio_hardwareinterace)
Android audio system(audio_hardwareinterace)
 
Rust言語紹介
Rust言語紹介Rust言語紹介
Rust言語紹介
 
Groovy on the Shell
Groovy on the ShellGroovy on the Shell
Groovy on the Shell
 
The Browser Environment - A Systems Programmer's Perspective
The Browser Environment - A Systems Programmer's PerspectiveThe Browser Environment - A Systems Programmer's Perspective
The Browser Environment - A Systems Programmer's Perspective
 
Hom Class
Hom ClassHom Class
Hom Class
 
Hom Class
Hom ClassHom Class
Hom Class
 
zinno
zinnozinno
zinno
 
Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02
 
C++の話(本当にあった怖い話)
C++の話(本当にあった怖い話)C++の話(本当にあった怖い話)
C++の話(本当にあった怖い話)
 
Php7 hashtable
Php7 hashtablePhp7 hashtable
Php7 hashtable
 
ZeroMQ: Messaging Made Simple
ZeroMQ: Messaging Made SimpleZeroMQ: Messaging Made Simple
ZeroMQ: Messaging Made Simple
 
Créer une base NoSQL en 1 heure
Créer une base NoSQL en 1 heureCréer une base NoSQL en 1 heure
Créer une base NoSQL en 1 heure
 

Similaire à Proxy Pattern in PHP Explained

Refactoring to symfony components
Refactoring to symfony componentsRefactoring to symfony components
Refactoring to symfony componentsMichael Peacock
 
Nginx Scripting - Extending Nginx Functionalities with Lua
Nginx Scripting - Extending Nginx Functionalities with LuaNginx Scripting - Extending Nginx Functionalities with Lua
Nginx Scripting - Extending Nginx Functionalities with LuaTony Fabeen
 
Devinsampa nginx-scripting
Devinsampa nginx-scriptingDevinsampa nginx-scripting
Devinsampa nginx-scriptingTony Fabeen
 
PhpUnit Best Practices
PhpUnit Best PracticesPhpUnit Best Practices
PhpUnit Best PracticesEdorian
 
Security Challenges in Node.js
Security Challenges in Node.jsSecurity Challenges in Node.js
Security Challenges in Node.jsWebsecurify
 
Making the most of 2.2
Making the most of 2.2Making the most of 2.2
Making the most of 2.2markstory
 
PHP in 2018 - Q4 - AFUP Limoges
PHP in 2018 - Q4 - AFUP LimogesPHP in 2018 - Q4 - AFUP Limoges
PHP in 2018 - Q4 - AFUP Limoges✅ William Pinaud
 
Build a custom (micro)framework with ZF2 Components (as building blocks)
Build a custom (micro)framework with ZF2 Components (as building blocks)Build a custom (micro)framework with ZF2 Components (as building blocks)
Build a custom (micro)framework with ZF2 Components (as building blocks)Corley S.r.l.
 
Legacy applications - 4Developes konferencja, Piotr Pasich
Legacy applications  - 4Developes konferencja, Piotr PasichLegacy applications  - 4Developes konferencja, Piotr Pasich
Legacy applications - 4Developes konferencja, Piotr PasichPiotr Pasich
 
perl usage at database applications
perl usage at database applicationsperl usage at database applications
perl usage at database applicationsJoe Jiang
 
PHP Enums - PHPCon Japan 2021
PHP Enums - PHPCon Japan 2021PHP Enums - PHPCon Japan 2021
PHP Enums - PHPCon Japan 2021Ayesh Karunaratne
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleHugo Hamon
 
Debugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 VersionDebugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 VersionIan Barber
 
Functional Programming In Java
Functional Programming In JavaFunctional Programming In Java
Functional Programming In JavaAndrei Solntsev
 

Similaire à Proxy Pattern in PHP Explained (20)

Refactoring to symfony components
Refactoring to symfony componentsRefactoring to symfony components
Refactoring to symfony components
 
OOP in Rust
OOP in RustOOP in Rust
OOP in Rust
 
Nginx Scripting - Extending Nginx Functionalities with Lua
Nginx Scripting - Extending Nginx Functionalities with LuaNginx Scripting - Extending Nginx Functionalities with Lua
Nginx Scripting - Extending Nginx Functionalities with Lua
 
Devinsampa nginx-scripting
Devinsampa nginx-scriptingDevinsampa nginx-scripting
Devinsampa nginx-scripting
 
PhpUnit Best Practices
PhpUnit Best PracticesPhpUnit Best Practices
PhpUnit Best Practices
 
Security Challenges in Node.js
Security Challenges in Node.jsSecurity Challenges in Node.js
Security Challenges in Node.js
 
Intro to The PHP SPL
Intro to The PHP SPLIntro to The PHP SPL
Intro to The PHP SPL
 
Making the most of 2.2
Making the most of 2.2Making the most of 2.2
Making the most of 2.2
 
PHP in 2018 - Q4 - AFUP Limoges
PHP in 2018 - Q4 - AFUP LimogesPHP in 2018 - Q4 - AFUP Limoges
PHP in 2018 - Q4 - AFUP Limoges
 
Build a custom (micro)framework with ZF2 Components (as building blocks)
Build a custom (micro)framework with ZF2 Components (as building blocks)Build a custom (micro)framework with ZF2 Components (as building blocks)
Build a custom (micro)framework with ZF2 Components (as building blocks)
 
Legacy applications - 4Developes konferencja, Piotr Pasich
Legacy applications  - 4Developes konferencja, Piotr PasichLegacy applications  - 4Developes konferencja, Piotr Pasich
Legacy applications - 4Developes konferencja, Piotr Pasich
 
perl usage at database applications
perl usage at database applicationsperl usage at database applications
perl usage at database applications
 
JavaFX, because you're worth it
JavaFX, because you're worth itJavaFX, because you're worth it
JavaFX, because you're worth it
 
Scala 2 + 2 > 4
Scala 2 + 2 > 4Scala 2 + 2 > 4
Scala 2 + 2 > 4
 
PHP Enums - PHPCon Japan 2021
PHP Enums - PHPCon Japan 2021PHP Enums - PHPCon Japan 2021
PHP Enums - PHPCon Japan 2021
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et Pimple
 
Blocks+gcd入門
Blocks+gcd入門Blocks+gcd入門
Blocks+gcd入門
 
Debugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 VersionDebugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 Version
 
Functional Programming In Java
Functional Programming In JavaFunctional Programming In Java
Functional Programming In Java
 

Dernier

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 

Dernier (20)

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 

Proxy Pattern in PHP Explained

  • 1. PROXY PATTERN IN PHP
  • 2. MARCO PIVETTA Doctrine core team Zf2 contributor Wasting time on: OcraDiCompiler OcraServiceManager OcraCachedViewResolver Doctrine ZF2 Modules ZeffMu AssetManager KJSencha Follow @Ocramius Follow @Ocramius
  • 3. WHAT IS A PROXY? A proxy is generally an object whose interface is a layer between us and a different object with the same interface.
  • 4.
  • 5. Simplified, in PHP Even if we're not implementing an interface, the interface of C s o e P o yis the same as the utmrrx one of C s o e utmr
  • 6. WHERE TO USE PROXIES? As of the LSP , a proxy can be used in any place where the "proxied" object can be used.
  • 7. WHEN TO USE A PROXY? Lazy loading Remote objects Smart reference/Weak reference Protection AOP Null object fallback
  • 8. LAZY LOADING We may want to use lazy loading to avoid IO operations or heavy loading operation until really needed
  • 9. LAZY LOADING PATTERNS 1. Virtual Object 2. Value Holder 3. Ghost Object
  • 10. VIRTUAL OBJECT An object whose properties are all set to n l , and where each access to the ul properties is tracked. Access triggers lazy loading on the property.
  • 11. VALUE HOLDER An object that can hold an instance of the original proxied object, and loads it only when needed.
  • 12. GHOST OBJECT An object whose properties are the same of the proxied object, but n l . ul Accessing any method causes loading of the properties. Doctrine Proxies are generated this way.
  • 13. VALUE HOLDER EXAMPLE (1/3) casIae{ ls mg pbi fnto _cntut$ah { ulc ucin _osrc(pt) $hs>mg =iaeraermpg$ ti-iae mgcetfoje(p ah; t) } pbi fnto gtie){ ulc ucin eSz( rtr aryiaex$hs>mg) i eun ra(mgs(ti-iae, mgs(ti-iae) aey$hs>mg); } }
  • 14. 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(; } }
  • 15. VALUE HOLDER EXAMPLE (3/3) $m1=nwIaerx(/aht/mg1jg) ig e mgPoy'pt/oiae.p' ; vrdm(eoygtuae);/ ~0K a_upmmr_e_sg() / 20b $m2=nwIaerx(/aht/mg2jg) ig e mgPoy'pt/oiae.p' ; vrdm(eoygtuae);/ ~0K a_upmmr_e_sg() / 20b $m3=nwIaerx(/aht/mg3jg) ig e mgPoy'pt/oiae.p' ; vrdm(eoygtuae);/ ~0K a_upmmr_e_sg() / 20b $ie =$m1>eSz(; sz1 ig-gtie) vrdm(eoygtuae);/ ~M a_upmmr_e_sg() / 4b $ie =$m2>eSz(; sz2 ig-gtie) vrdm(eoygtuae);/ ~M a_upmmr_e_sg() / 8b
  • 16. LAZY LOADING PROS/CONS Advantages Low memory impact Low overhead Easy to implement Useful to determine object "dirty" status Dis-advantages Not optimal for data that is always loaded Lazy loading means lazy failing
  • 17. REMOTE OBJECT It basically is a specific form of lazy loading
  • 18. 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>aa'et] eun ti-dt[tx'; } }
  • 19. REMOTE OBJECT EXAMPLE (2/3) casTetrx etnsTet{ ls wePoy xed we poetd$p;poetd$we;poe rtce ai rtce tet rtc td$d e i; pbi fnto _cntutTitrp $ ulc ucin _osrc(wteAi ai $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(; } }
  • 20. REMOTE OBJECT EXAMPLE (3/3) $we =nwTetary'et = 'rxe i tet e we(ra(tx' > Pois nPP') H!); vrdm(tet>eTx() / 'rxe i P a_up$we-gtet); / Pois n H! P' $p =nwTitrp(*yda*) / z,b ai e wteAi/ ad /; / f u z,ec z t $eoewe =nwTetrx(ai 20478 rmtTet e wePoy$p, 8630 98850; 6366) vrdm(rmtTet>eTx() / 'we a_up$eoewe-gtet); / Tet tx! et' $eoewe =nwTetrx(ai 20478 rmtTet e wePoy$p, 8630 98851; 6366) vrdm(rmtTet>eTx() / 'nte a_up$eoewe-gtet); / Aoh rtx! et'
  • 21. REMOTE OBJECT PROS/CONS Advantages Abstraction of a remote object You can re-define the proxied object's API locally Dis-advantages To use such a proxy, you almost always need a configured remote client Remote objects fail very easily
  • 22. SMART REFERENCE Smart reference can be used to: swap the proxied object at runtime reference singletons or use internal static registries Optimize memory usage
  • 23. SMART REFERENCE WITH WEAKREF Using Weakref to save memory on long-running processes casIaerx 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-i aee-vld) { gRf>ai() $hs>mgRf=nwWaRfnw ti-iaee e eke(e Iae$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) } }
  • 24. SMART REFERENCE WITH A REGISTRY casIaerx 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(; } }
  • 25. SMART REFERENCE PROS/CONS Mainly memory usage, but it depends on how you setup your "smart" reference
  • 26. PROTECTION PROXY Protection proxy comes into play when you want to transparently limit access to an API through a set of rules (ACL/limits)
  • 27. PROTECTION PROXY (1/2) casRmtAirx etnsRmtAi{ ls eoepPoy xed eoep poetd$on =0 rtce cut ; pbi fnto _cntutRmtAi$ ulc ucin _osrc(eoep a p,$ii){ i lmt $hs>p =$p;$hs>ii =$ ti-ai ai ti-lmt l ii; mt } piaefnto cut){ rvt ucin on( i (+ti-cut>$hs>ii){ f +$hs>on ti-lmt trwnwRmtAiii(SAP ho e eoepLmt'TH! '; ) } } pbi fnto dSuf){ ulc ucin otf( $hs>on(; ti-cut) rtr $hs>p-dSuf) eun ti-ai>otf(; } }
  • 28. PROTECTION PROXY (2/2) $p =nwRmtAirx(e RmtAi/ . ai e eoepPoynw eoep(* . .*) 5) /, 0; wie(){ hl 1 $p-dSuf) / RmtAiii ecp ai>otf(; / eoepLmt xet in o! }
  • 29. PROTECTION PROXY PROS/CONS Advantages Transparent filtering or limiting of access to an object Dis-advantages Modifies proxied object behavior! More like a decorator!
  • 30. NULL OBJECT FALLBACK PROXY A null object is an object that implements an interface, but produces no side effects. It replaces n l . ul Using null objects allows us to work with the assumption that an object will always be available, reducing checks against n l by a lot. ul
  • 31. NULL OBJECT FALLBACK PROXY EXAMPLE casCsoePoyetnsCsoe { 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 ulutm r) (; } } pbi fnto dSuf){ ulc ucin otf( rtr $hs>utmr>otf(; eun ti-csoe-dSuf) } }
  • 32. NULL OBJECT FALLBACK PROXY PROS Performance (with small # of instances) Reduced NPaths, therefore code is easier to test
  • 33. AOP AND PROXIES Proxies basically enable us to have logic between us and any object, making AOP easy even when the language doesn't allow it. We can use code generation to create on-the-fly proxies with our custom AOP logic executed pre- and post- any method of the proxied object.
  • 34. AOP EXAMPLES /* * *@Oah(t=60 APCcetl30) */ pbi fnto dHaytf( { ulc ucin oevSuf) / [.] / .. } Becomes: pbi fnto dHaytf( { ulc ucin oevSuf) i(cce =$hs>ah-gt'oevS f$ahd ti-cce>e(dHayt uf,fn_e_rs)){ f' ucgtag() rtr $ahd eun cce; } $eun=$hs>rgnlbet>oevS rtr ti-oiiaOjc-dHay tf(; uf) $hs>ah-st$eun 'oevSuf ti-cce>e(rtr, dHaytf' ,fn_e_rs); ucgtag() rtr $eun eun rtr; }
  • 36. IMPLEMENTING THE PUBLIC API 1. The Proxy class MUST extend the proxied class 2. Each of the proxied methods must be rewritten 3. Proxies should be serializable 4. Proxies should handle public properties
  • 37. PUBLIC PROPERTIES PROXYING casCsoe { ls utmr pbi $ae ulc nm; pbi $unm; ulc srae } casCsoePoyetnsCsoe { ls utmrrx xed utmr pbi fnto _cntutCsoe $u ulc ucin _osrc(utmr cs tmr { 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 }
  • 38. A COMPLETE GHOST OBJECT IMPLEMENTATION https://gist.github.com/4038004