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
Ad

Recommended

Things I wish web graduates knew
Things I wish web graduates knew
Lorna Mitchell
 
Web services in PHP using the NuSOAP library
Web services in PHP using the NuSOAP library
Fulvio Corno
 
Intoduction to php web services and json
Intoduction to php web services and json
baabtra.com - No. 1 supplier of quality freshers
 
Webservice for android ppt
Webservice for android ppt
santosh lamba
 
OAuth: Trust Issues
OAuth: Trust Issues
Lorna Mitchell
 
Web services tutorial
Web services tutorial
Lorna Mitchell
 
Restful web services with java
Restful web services with java
Vinay Gopinath
 
RESTful Web Services with JAX-RS
RESTful Web Services with JAX-RS
Carol McDonald
 
Creating And Consuming Web Services In Php 5
Creating And Consuming Web Services In Php 5
Michael Girouard
 
RestFull Webservices with JAX-RS
RestFull Webservices with JAX-RS
Neil Ghosh
 
Consuming RESTful services in PHP
Consuming RESTful services in PHP
Zoran Jeremic
 
Developing RESTful WebServices using Jersey
Developing RESTful WebServices using Jersey
b_kathir
 
Using Java to implement RESTful Web Services: JAX-RS
Using Java to implement RESTful Web Services: JAX-RS
Katrien Verbert
 
RESTful Web Services
RESTful Web Services
Martin Necasky
 
Making Java REST with JAX-RS 2.0
Making Java REST with JAX-RS 2.0
Dmytro Chyzhykov
 
Develop webservice in PHP
Develop webservice in PHP
Sanil Subhash Chandra Bose
 
REST API Recommendations
REST API Recommendations
Jeelani Shaik
 
ASP.NET WEB API
ASP.NET WEB API
Thang Chung
 
RESTing with JAX-RS
RESTing with JAX-RS
Ezewuzie Emmanuel Okafor
 
Introduction to RESTful Webservices in JAVA
Introduction to RESTful Webservices in JAVA
psrpatnaik
 
RESTful http_patterns_antipatterns
RESTful http_patterns_antipatterns
Jan Algermissen
 
Java Web Programming [5/9] : EL, JSTL and Custom Tags
Java Web Programming [5/9] : EL, JSTL and Custom Tags
IMC Institute
 
Webservices
Webservices
s4al_com
 
RESTful services with JAXB and JPA
RESTful services with JAXB and JPA
Shaun Smith
 
Best Practice in API Design
Best Practice in API Design
Lorna Mitchell
 
Spring Web Service, Spring Integration and Spring Batch
Spring Web Service, Spring Integration and Spring Batch
Eberhard Wolff
 
Ws rest
Ws rest
patriknw
 
Android App Development 06 : Network & Web Services
Android App Development 06 : Network & Web Services
Anuchit Chalothorn
 
Java reflection
Java reflection
Ranjith Chaz
 
Java Reflection @KonaTechAdda
Java Reflection @KonaTechAdda
Md Imran Hasan Hira
 

More Related Content

What's hot (20)

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

Viewers also liked (18)

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

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

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

More from Matthieu Aubry (17)

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

Recently uploaded (20)

Techniques for Automatic Device Identification and Network Assignment.pdf
Techniques for Automatic Device Identification and Network Assignment.pdf
Priyanka Aash
 
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik
 
Daily Lesson Log MATATAG ICT TEchnology 8
Daily Lesson Log MATATAG ICT TEchnology 8
LOIDAALMAZAN3
 
cnc-processing-centers-centateq-p-110-en.pdf
cnc-processing-centers-centateq-p-110-en.pdf
AmirStern2
 
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
Fwdays
 
OWASP Barcelona 2025 Threat Model Library
OWASP Barcelona 2025 Threat Model Library
PetraVukmirovic
 
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Josef Weingand
 
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
Priyanka Aash
 
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Safe Software
 
Curietech AI in action - Accelerate MuleSoft development
Curietech AI in action - Accelerate MuleSoft development
shyamraj55
 
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
 
From Manual to Auto Searching- FME in the Driver's Seat
From Manual to Auto Searching- FME in the Driver's Seat
Safe Software
 
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
 
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
Priyanka Aash
 
Mastering AI Workflows with FME by Mark Döring
Mastering AI Workflows with FME by Mark Döring
Safe Software
 
Securing AI - There Is No Try, Only Do!.pdf
Securing AI - There Is No Try, Only Do!.pdf
Priyanka Aash
 
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Priyanka Aash
 
9-1-1 Addressing: End-to-End Automation Using FME
9-1-1 Addressing: End-to-End Automation Using FME
Safe Software
 
Techniques for Automatic Device Identification and Network Assignment.pdf
Techniques for Automatic Device Identification and Network Assignment.pdf
Priyanka Aash
 
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik
 
Daily Lesson Log MATATAG ICT TEchnology 8
Daily Lesson Log MATATAG ICT TEchnology 8
LOIDAALMAZAN3
 
cnc-processing-centers-centateq-p-110-en.pdf
cnc-processing-centers-centateq-p-110-en.pdf
AmirStern2
 
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
Fwdays
 
OWASP Barcelona 2025 Threat Model Library
OWASP Barcelona 2025 Threat Model Library
PetraVukmirovic
 
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Josef Weingand
 
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
Priyanka Aash
 
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Safe Software
 
Curietech AI in action - Accelerate MuleSoft development
Curietech AI in action - Accelerate MuleSoft development
shyamraj55
 
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
 
From Manual to Auto Searching- FME in the Driver's Seat
From Manual to Auto Searching- FME in the Driver's Seat
Safe Software
 
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
 
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
Priyanka Aash
 
Mastering AI Workflows with FME by Mark Döring
Mastering AI Workflows with FME by Mark Döring
Safe Software
 
Securing AI - There Is No Try, Only Do!.pdf
Securing AI - There Is No Try, Only Do!.pdf
Priyanka Aash
 
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Priyanka Aash
 
9-1-1 Addressing: End-to-End Automation Using FME
9-1-1 Addressing: End-to-End Automation Using FME
Safe Software
 

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