SlideShare a Scribd company logo
Easy Web Services   using PHP reflection API phplondon, Dec 4 th  2008
Reflection ?
http://www.flickr.com/photos/bcnbits/368112752/
Reflection In computer science, reflection is the process by which a computer program can observe and modify its own structure and behaviour.
Reflection in PHP5 reverse-engineer classes,  interfaces,  exceptions functions Methods Parameters properties extensions retrieve doc comments for  functions,  classes and  methods.
Eg. Reflection Method class  ReflectionMethod  extends  […] {   public  bool isFinal ()     public  bool isAbstract ()     public  bool isPublic ()     public  bool isPrivate ()     public  bool isProtected ()     public  bool isStatic ()     public  bool isConstructor ()     public  bool isDestructor () […..]     public  string getFileName ()     public  int getStartLine ()     public  int getEndLine ()     public  string getDocComment ()     public array  getStaticVariables ()
Eg. Reflection Method class  Randomizer {          /**       * Returns randomly 0 or 1       * @return  int      */        final public static function  get ()     {         return rand( 0, 1);     } } // Create an instance of the ReflectionMethod class $method  = new  ReflectionMethod ( ‘ Randomizer ' ,  get' ); echo  $method -> isConstructor () ?  'the constructor'  :  'a regular method‘ ; printf ( "---> Documentation:\n %s\n" ,  var_export ( $method -> getDocComment (),  1 ));
Reflection is useful for  Why reverse engineer comments in code?  Easy to generate documentation. Unit tests framework: mockup objects, function test*, etc. Automatic serializations of object: your code defines your data, your objects can be serialized automatically, converted in JSON, etc. $reflectionClass  =  new  ReflectionClass( 'ClassIsData' ); $properties  =  $reflectionClass- >getProperties(); $property ->getName();  $property ->getValue(  $instance  );
Reflection is useful for  Annotations, eg. in PHP Unit In this example the test will fail because it doesn’t throw the InvalidArgumentException
Easy Web Services   Simple use case
Watch out, you will see code   in slides!!!
class  Users { /** *  @return  array the list of all the users */ static public function  getUsers( $limit  = 10) { // each API method can have different permission requirements Access::checkUserHasPermission( 'admin' ); return  Registry::get( 'db' )->fetchAll( " SELECT *  FROM users    LIMIT $limit" ); } } Use case: you have this class in your system: You want this class and the public methods to be automatically available in a REST service, so you can call:  http://myService.net/?module=Users.getUsers&limit=100 And get the result (eg. in XML)
// simple call to the REST API via http $users  = file_get_contents(  "http://service/API/" . "?method=Users.getUsers&limit=100" ); // we also want to call it from within our existing php code  FrontController::getInstance()->init();  // init DB, logger, auth, etc. $request  =  new  Request( 'method=Users.getUsers&limit=100' ); $result  =  $request ->process(); How we want to call it (1/2)
// ResponseBuilder object can convert the data in XML, JSON, CSV // by converting your API returned value (from array, int, object, etc)  $request  =  new  Request( '  method=Users.getUsers &limit=100   &format=JSON' ); $XmlResult  =  $request ->process(); // possible to add token_based authentication: all API methods call helper // class that checks that the token has the right permissions  $request  =  new  Request( 'method=Users.getUsers&token_auth=puiwrtertwoc98' ); $result  =  $request ->process(); How we want to call it (2/2)
The concept Request comes in, forwarded to Proxy that does the Reflection magic: calls the method on the right class, with the right parameters mapped.
class  Request  { protected  $request ; function  __construct( $requestString  = null) { if (is_null( $requestString )) { $request  =  $_REQUEST ; }  else  { $request  = parse_str( $requestString ); } $this ->request =  $request ; } function  process() { $responseBuilder  =  new  ResponseBuilder( $this ->request); try  { // eg. get the "Users.getUsers" $methodToCall  = Helper::sanitizeInputVariable( 'method' ,  $this ->request); list ( $className ,  $method )  = e xplode( '.' , $methodToCall ); $proxy  = Proxy::getInstance(); $returnedValue  =  $proxy ->call( $className ,  $method ,  $this ->request ); // return the response after applying standard filters, converting format,.. $response  =  $responseBuilder ->getResponse( $returnedValue ); }  catch (Exception  $e  ) { // exception is forwarded to ResponseBuilder to be converted in XML/JSON,.. $response  =  $responseBuilder ->getResponseException(  $e  ); } return  $response ; } } $request  =  new  Request(  'method=Users.getUsers&limit=100' ); $result  =  $request ->process();
class  Proxy { function  call( $className ,  $methodName ,  $request ) {   $this->setContext( $className ,  $methodName ,  $request); $this ->loadClassMetadata(); $this ->checkMethodExists(); $this ->checkParametersAreSet();   $parameterValues = $this ->getParametersValues(); $object  = call_user_func( array ( $className ,  "getInstance" )); $timer  =  new  Timer; $returnedValue  = call_user_func_array(  array ( $object ,  $methodName ), $parameterValues ); Registry::get( 'logger_api' )->log( $className ,  $methodName ,  $ parameterValues $timer ->getTimeMs(), $returnedValue) ;  return  $returnedValue ; } function  loadClassMetadata( $className ) { $reflectionClass  =  new  ReflectionClass( $className );   foreach ( $reflectionClass ->getMethods()  as  $method ) { $this ->loadMethodMetadata( $className ,  $method ); } } [...] }
Conclusion Similar pattern as FrontController / Dispatcher One entry point to your Models. You can then add: Caching Logging Authentication Eg. If your app is data-centric, the ResponseBuilder could apply set of filters. You could for example specify custom filters to be apply to API calls in the RequestString: $request  =  new  Request( ' method=Analytics.getUsers &filter_sort=name-desc &filter_search=(pattern)' );
... and use the Proxy class to generate your API documentation (from the code, and by reverse engineering your method comments)
Questions ?
References This pattern is used in the open source Piwik project http://piwik.org View the code on http://dev.piwik.org/svn/trunk/core/API/ How to design an API: best practises, concepts   http://piwik.org/blog/2008/01/how-to-design-an-api-best-practises-concepts-technical-aspects/ PHP: Reflection – Manual   http://uk.php.net/oop5.reflection Declarative Development Using Annotations In PHP http://www.slideshare.net/stubbles/declarative-development-using-annotations-in-php Presentation under license #cc-by-sa, by Matthieu Aubry

More Related Content

What's hot (20)

PDF
Creating And Consuming Web Services In Php 5
Michael Girouard
 
ODP
RestFull Webservices with JAX-RS
Neil Ghosh
 
PDF
Consuming RESTful services in PHP
Zoran Jeremic
 
PPT
Developing RESTful WebServices using Jersey
b_kathir
 
PPT
Using Java to implement RESTful Web Services: JAX-RS
Katrien Verbert
 
PPTX
RESTful Web Services
Martin Necasky
 
PDF
Making Java REST with JAX-RS 2.0
Dmytro Chyzhykov
 
PPT
Develop webservice in PHP
Sanil Subhash Chandra Bose
 
PDF
REST API Recommendations
Jeelani Shaik
 
PPTX
ASP.NET WEB API
Thang Chung
 
ODP
RESTing with JAX-RS
Ezewuzie Emmanuel Okafor
 
PPTX
Introduction to RESTful Webservices in JAVA
psrpatnaik
 
PDF
RESTful http_patterns_antipatterns
Jan Algermissen
 
PDF
Java Web Programming [5/9] : EL, JSTL and Custom Tags
IMC Institute
 
PPTX
Webservices
s4al_com
 
PPT
RESTful services with JAXB and JPA
Shaun Smith
 
PDF
Best Practice in API Design
Lorna Mitchell
 
PDF
Spring Web Service, Spring Integration and Spring Batch
Eberhard Wolff
 
PDF
Ws rest
patriknw
 
PDF
Android App Development 06 : Network & Web Services
Anuchit Chalothorn
 
Creating And Consuming Web Services In Php 5
Michael Girouard
 
RestFull Webservices with JAX-RS
Neil Ghosh
 
Consuming RESTful services in PHP
Zoran Jeremic
 
Developing RESTful WebServices using Jersey
b_kathir
 
Using Java to implement RESTful Web Services: JAX-RS
Katrien Verbert
 
RESTful Web Services
Martin Necasky
 
Making Java REST with JAX-RS 2.0
Dmytro Chyzhykov
 
Develop webservice in PHP
Sanil Subhash Chandra Bose
 
REST API Recommendations
Jeelani Shaik
 
ASP.NET WEB API
Thang Chung
 
RESTing with JAX-RS
Ezewuzie Emmanuel Okafor
 
Introduction to RESTful Webservices in JAVA
psrpatnaik
 
RESTful http_patterns_antipatterns
Jan Algermissen
 
Java Web Programming [5/9] : EL, JSTL and Custom Tags
IMC Institute
 
Webservices
s4al_com
 
RESTful services with JAXB and JPA
Shaun Smith
 
Best Practice in API Design
Lorna Mitchell
 
Spring Web Service, Spring Integration and Spring Batch
Eberhard Wolff
 
Ws rest
patriknw
 
Android App Development 06 : Network & Web Services
Anuchit Chalothorn
 

Viewers also liked (18)

PDF
Java reflection
Ranjith Chaz
 
PPTX
Java Reflection @KonaTechAdda
Md Imran Hasan Hira
 
PPTX
Java Exploit Analysis .
Rahul Sasi
 
PPTX
Java notes(OOP) jkuat IT esection
Arc Keepers Solutions
 
PPTX
Reflection in Java
Nikhil Bhardwaj
 
PDF
Java Reflection Explained Simply
Ciaran McHale
 
PDF
Integrating Google APIs into Your Applications
Chris Schalk
 
PPTX
Image galley ppt
Chaitanya Chandurkar
 
PDF
Image Optimization for the Web at php|works
Stoyan Stefanov
 
PDF
Google drive for nonprofits webinar
Craig Grella
 
PPT
PHP Project PPT
Pankil Agrawal
 
PPT
Php Presentation
Manish Bothra
 
PDF
LinkedIn Learning | What We're Learning About Learning
LinkedIn Learning Solutions
 
PPTX
How To Embed SlideShare Shows Into WordPress.com
Kathy Gill
 
PDF
How to prepare for a long distance hiking trip
Austin Gratham
 
PPT
Introduction to PHP
Jussi Pohjolainen
 
PDF
State of the Word 2011
photomatt
 
PDF
Build Features, Not Apps
Natasha Murashev
 
Java reflection
Ranjith Chaz
 
Java Reflection @KonaTechAdda
Md Imran Hasan Hira
 
Java Exploit Analysis .
Rahul Sasi
 
Java notes(OOP) jkuat IT esection
Arc Keepers Solutions
 
Reflection in Java
Nikhil Bhardwaj
 
Java Reflection Explained Simply
Ciaran McHale
 
Integrating Google APIs into Your Applications
Chris Schalk
 
Image galley ppt
Chaitanya Chandurkar
 
Image Optimization for the Web at php|works
Stoyan Stefanov
 
Google drive for nonprofits webinar
Craig Grella
 
PHP Project PPT
Pankil Agrawal
 
Php Presentation
Manish Bothra
 
LinkedIn Learning | What We're Learning About Learning
LinkedIn Learning Solutions
 
How To Embed SlideShare Shows Into WordPress.com
Kathy Gill
 
How to prepare for a long distance hiking trip
Austin Gratham
 
Introduction to PHP
Jussi Pohjolainen
 
State of the Word 2011
photomatt
 
Build Features, Not Apps
Natasha Murashev
 
Ad

Similar to Easy rest service using PHP reflection api (20)

PPTX
Building a horizontally scalable API in php
Wade Womersley
 
PPTX
Php meetup 20130912 reflection
JoelRSimpson
 
PDF
A resource oriented framework using the DI/AOP/REST triangle
Akihito Koriyama
 
PDF
Practical PHP 5.3
Nate Abele
 
PPT
Go OO! - Real-life Design Patterns in PHP 5
Stephan Schmidt
 
PPTX
Introduction to Monsoon PHP framework
Krishna Srikanth Manda
 
PPTX
Adding Dependency Injection to Legacy Applications
Sam Hennessy
 
PDF
Introduction to Zend Framework web services
Michelangelo van Dam
 
PDF
Object Oriented Programming with PHP 5 - More OOP
Wildan Maulana
 
PDF
Migrating to dependency injection
Josh Adell
 
PPT
Writing Friendly libraries for CodeIgniter
CodeIgniter Conference
 
PPT
Reflection-In-PHP
Mindfire Solutions
 
PDF
Dci in PHP
Herman Peeren
 
PDF
Be pragmatic, be SOLID
Krzysztof Menżyk
 
PDF
4Developers 2015: Be pragmatic, be SOLID - Krzysztof Menżyk
PROIDEA
 
PDF
PHP unserialization vulnerabilities: What are we missing?
Sam Thomas
 
PPTX
Modularizing RESTful Web Service Management with Aspect Oriented Programming
Widhian Bramantya
 
ODP
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
King Foo
 
PDF
Api Design
sumithra jonnalagadda
 
KEY
Zend framework service
Michelangelo van Dam
 
Building a horizontally scalable API in php
Wade Womersley
 
Php meetup 20130912 reflection
JoelRSimpson
 
A resource oriented framework using the DI/AOP/REST triangle
Akihito Koriyama
 
Practical PHP 5.3
Nate Abele
 
Go OO! - Real-life Design Patterns in PHP 5
Stephan Schmidt
 
Introduction to Monsoon PHP framework
Krishna Srikanth Manda
 
Adding Dependency Injection to Legacy Applications
Sam Hennessy
 
Introduction to Zend Framework web services
Michelangelo van Dam
 
Object Oriented Programming with PHP 5 - More OOP
Wildan Maulana
 
Migrating to dependency injection
Josh Adell
 
Writing Friendly libraries for CodeIgniter
CodeIgniter Conference
 
Reflection-In-PHP
Mindfire Solutions
 
Dci in PHP
Herman Peeren
 
Be pragmatic, be SOLID
Krzysztof Menżyk
 
4Developers 2015: Be pragmatic, be SOLID - Krzysztof Menżyk
PROIDEA
 
PHP unserialization vulnerabilities: What are we missing?
Sam Thomas
 
Modularizing RESTful Web Service Management with Aspect Oriented Programming
Widhian Bramantya
 
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
King Foo
 
Zend framework service
Michelangelo van Dam
 
Ad

More from Matthieu Aubry (17)

ODP
State of Piwik 2015 - Berlin community meetup
Matthieu Aubry
 
PDF
Introduction to piwik analytics platform 2015
Matthieu Aubry
 
ODP
The making of the analytics platform of the future
Matthieu Aubry
 
ODP
Web Analytics for your ePortfolio
Matthieu Aubry
 
PDF
Intro to Piwik project - 2014
Matthieu Aubry
 
PDF
Piwik at INTEROP TOKYO, June 2013
Matthieu Aubry
 
PDF
Piwik Analytics - Marketing Brochure
Matthieu Aubry
 
PPTX
Piwik in Japan Osc2013 photo
Matthieu Aubry
 
PDF
Piwik オープンソースウェブ解析 2011年資料 - Piwik Restrospective
Matthieu Aubry
 
PPT
Piwik Japan - interrop2012 in tokyo
Matthieu Aubry
 
PDF
Piwik presentation 2011
Matthieu Aubry
 
PPT
Piwik Presentation
Matthieu Aubry
 
PPT
Piwik Retrospective 2008
Matthieu Aubry
 
PPT
Piwik - open source web analytics
Matthieu Aubry
 
PPT
Piwik - build a developer community
Matthieu Aubry
 
PPT
Piwik Presentation
Matthieu Aubry
 
PPT
Dashboard - definition, examples
Matthieu Aubry
 
State of Piwik 2015 - Berlin community meetup
Matthieu Aubry
 
Introduction to piwik analytics platform 2015
Matthieu Aubry
 
The making of the analytics platform of the future
Matthieu Aubry
 
Web Analytics for your ePortfolio
Matthieu Aubry
 
Intro to Piwik project - 2014
Matthieu Aubry
 
Piwik at INTEROP TOKYO, June 2013
Matthieu Aubry
 
Piwik Analytics - Marketing Brochure
Matthieu Aubry
 
Piwik in Japan Osc2013 photo
Matthieu Aubry
 
Piwik オープンソースウェブ解析 2011年資料 - Piwik Restrospective
Matthieu Aubry
 
Piwik Japan - interrop2012 in tokyo
Matthieu Aubry
 
Piwik presentation 2011
Matthieu Aubry
 
Piwik Presentation
Matthieu Aubry
 
Piwik Retrospective 2008
Matthieu Aubry
 
Piwik - open source web analytics
Matthieu Aubry
 
Piwik - build a developer community
Matthieu Aubry
 
Piwik Presentation
Matthieu Aubry
 
Dashboard - definition, examples
Matthieu Aubry
 

Recently uploaded (20)

PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 

Easy rest service using PHP reflection api

  • 1. Easy Web Services using PHP reflection API phplondon, Dec 4 th 2008
  • 4. Reflection In computer science, reflection is the process by which a computer program can observe and modify its own structure and behaviour.
  • 5. Reflection in PHP5 reverse-engineer classes, interfaces, exceptions functions Methods Parameters properties extensions retrieve doc comments for functions, classes and methods.
  • 6. Eg. Reflection Method class  ReflectionMethod  extends  […] { public  bool isFinal ()     public  bool isAbstract ()     public  bool isPublic ()     public  bool isPrivate ()     public  bool isProtected ()     public  bool isStatic ()     public  bool isConstructor ()     public  bool isDestructor () […..]     public  string getFileName ()     public  int getStartLine ()     public  int getEndLine ()     public  string getDocComment ()     public array  getStaticVariables ()
  • 7. Eg. Reflection Method class  Randomizer {          /**       * Returns randomly 0 or 1       * @return  int      */      final public static function  get ()     {         return rand( 0, 1);     } } // Create an instance of the ReflectionMethod class $method  = new  ReflectionMethod ( ‘ Randomizer ' ,  get' ); echo $method -> isConstructor () ?  'the constructor'  :  'a regular method‘ ; printf ( "---> Documentation:\n %s\n" ,  var_export ( $method -> getDocComment (),  1 ));
  • 8. Reflection is useful for Why reverse engineer comments in code? Easy to generate documentation. Unit tests framework: mockup objects, function test*, etc. Automatic serializations of object: your code defines your data, your objects can be serialized automatically, converted in JSON, etc. $reflectionClass  = new ReflectionClass( 'ClassIsData' ); $properties = $reflectionClass- >getProperties(); $property ->getName(); $property ->getValue( $instance );
  • 9. Reflection is useful for Annotations, eg. in PHP Unit In this example the test will fail because it doesn’t throw the InvalidArgumentException
  • 10. Easy Web Services Simple use case
  • 11. Watch out, you will see code in slides!!!
  • 12. class Users { /** * @return array the list of all the users */ static public function getUsers( $limit = 10) { // each API method can have different permission requirements Access::checkUserHasPermission( 'admin' ); return Registry::get( 'db' )->fetchAll( " SELECT * FROM users LIMIT $limit" ); } } Use case: you have this class in your system: You want this class and the public methods to be automatically available in a REST service, so you can call: http://myService.net/?module=Users.getUsers&limit=100 And get the result (eg. in XML)
  • 13. // simple call to the REST API via http $users = file_get_contents( "http://service/API/" . "?method=Users.getUsers&limit=100" ); // we also want to call it from within our existing php code FrontController::getInstance()->init(); // init DB, logger, auth, etc. $request = new Request( 'method=Users.getUsers&limit=100' ); $result = $request ->process(); How we want to call it (1/2)
  • 14. // ResponseBuilder object can convert the data in XML, JSON, CSV // by converting your API returned value (from array, int, object, etc) $request = new Request( ' method=Users.getUsers &limit=100 &format=JSON' ); $XmlResult = $request ->process(); // possible to add token_based authentication: all API methods call helper // class that checks that the token has the right permissions $request = new Request( 'method=Users.getUsers&token_auth=puiwrtertwoc98' ); $result = $request ->process(); How we want to call it (2/2)
  • 15. The concept Request comes in, forwarded to Proxy that does the Reflection magic: calls the method on the right class, with the right parameters mapped.
  • 16. class Request { protected $request ; function __construct( $requestString = null) { if (is_null( $requestString )) { $request = $_REQUEST ; } else { $request = parse_str( $requestString ); } $this ->request = $request ; } function process() { $responseBuilder = new ResponseBuilder( $this ->request); try { // eg. get the "Users.getUsers" $methodToCall = Helper::sanitizeInputVariable( 'method' , $this ->request); list ( $className , $method ) = e xplode( '.' , $methodToCall ); $proxy = Proxy::getInstance(); $returnedValue = $proxy ->call( $className , $method , $this ->request ); // return the response after applying standard filters, converting format,.. $response = $responseBuilder ->getResponse( $returnedValue ); } catch (Exception $e ) { // exception is forwarded to ResponseBuilder to be converted in XML/JSON,.. $response = $responseBuilder ->getResponseException( $e ); } return $response ; } } $request = new Request( 'method=Users.getUsers&limit=100' ); $result = $request ->process();
  • 17. class Proxy { function call( $className , $methodName , $request ) { $this->setContext( $className , $methodName , $request); $this ->loadClassMetadata(); $this ->checkMethodExists(); $this ->checkParametersAreSet(); $parameterValues = $this ->getParametersValues(); $object = call_user_func( array ( $className , "getInstance" )); $timer = new Timer; $returnedValue = call_user_func_array( array ( $object , $methodName ), $parameterValues ); Registry::get( 'logger_api' )->log( $className , $methodName , $ parameterValues $timer ->getTimeMs(), $returnedValue) ; return $returnedValue ; } function loadClassMetadata( $className ) { $reflectionClass = new ReflectionClass( $className ); foreach ( $reflectionClass ->getMethods() as $method ) { $this ->loadMethodMetadata( $className , $method ); } } [...] }
  • 18. Conclusion Similar pattern as FrontController / Dispatcher One entry point to your Models. You can then add: Caching Logging Authentication Eg. If your app is data-centric, the ResponseBuilder could apply set of filters. You could for example specify custom filters to be apply to API calls in the RequestString: $request = new Request( ' method=Analytics.getUsers &filter_sort=name-desc &filter_search=(pattern)' );
  • 19. ... and use the Proxy class to generate your API documentation (from the code, and by reverse engineering your method comments)
  • 21. References This pattern is used in the open source Piwik project http://piwik.org View the code on http://dev.piwik.org/svn/trunk/core/API/ How to design an API: best practises, concepts http://piwik.org/blog/2008/01/how-to-design-an-api-best-practises-concepts-technical-aspects/ PHP: Reflection – Manual http://uk.php.net/oop5.reflection Declarative Development Using Annotations In PHP http://www.slideshare.net/stubbles/declarative-development-using-annotations-in-php Presentation under license #cc-by-sa, by Matthieu Aubry