SlideShare uma empresa Scribd logo
1 de 21
Easy Web Services   using PHP reflection API phplondon, Dec 4 th  2008
Reflection ?
http://www.flickr.com/photos/bcnbits/368112752/
Reflection ,[object Object]
Reflection in PHP5 ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
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: %s" ,  var_export ( $method -> getDocComment (),  1 ));
Reflection is useful for  ,[object Object],[object Object],[object Object],$reflectionClass  =  new  ReflectionClass( 'ClassIsData' ); $properties  =  $reflectionClass- >getProperties(); $property ->getName();  $property ->getValue(  $instance  );
Reflection is useful for  ,[object Object],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 ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],$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 ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

Mais conteúdo relacionado

Mais procurados

Creating And Consuming Web Services In Php 5
Creating And Consuming Web Services In Php 5Creating And Consuming Web Services In Php 5
Creating And Consuming Web Services In Php 5
Michael Girouard
 
Consuming RESTful services in PHP
Consuming RESTful services in PHPConsuming RESTful services in PHP
Consuming RESTful services in PHP
Zoran Jeremic
 
Developing RESTful WebServices using Jersey
Developing RESTful WebServices using JerseyDeveloping 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-RSUsing Java to implement RESTful Web Services: JAX-RS
Using Java to implement RESTful Web Services: JAX-RS
Katrien Verbert
 
REST API Recommendations
REST API RecommendationsREST API Recommendations
REST API Recommendations
Jeelani Shaik
 
RESTful services with JAXB and JPA
RESTful services with JAXB and JPARESTful services with JAXB and JPA
RESTful services with JAXB and JPA
Shaun Smith
 
Android App Development 06 : Network & Web Services
Android App Development 06 : Network & Web ServicesAndroid App Development 06 : Network & Web Services
Android App Development 06 : Network & Web Services
Anuchit Chalothorn
 

Mais procurados (20)

Creating And Consuming Web Services In Php 5
Creating And Consuming Web Services In Php 5Creating And Consuming Web Services In Php 5
Creating And Consuming Web Services In Php 5
 
RestFull Webservices with JAX-RS
RestFull Webservices with JAX-RSRestFull Webservices with JAX-RS
RestFull Webservices with JAX-RS
 
Consuming RESTful services in PHP
Consuming RESTful services in PHPConsuming RESTful services in PHP
Consuming RESTful services in PHP
 
Developing RESTful WebServices using Jersey
Developing RESTful WebServices using JerseyDeveloping RESTful WebServices using Jersey
Developing RESTful WebServices using Jersey
 
Using Java to implement RESTful Web Services: JAX-RS
Using Java to implement RESTful Web Services: JAX-RSUsing Java to implement RESTful Web Services: JAX-RS
Using Java to implement RESTful Web Services: JAX-RS
 
RESTful Web Services
RESTful Web ServicesRESTful Web Services
RESTful Web Services
 
Making Java REST with JAX-RS 2.0
Making Java REST with JAX-RS 2.0Making Java REST with JAX-RS 2.0
Making Java REST with JAX-RS 2.0
 
Develop webservice in PHP
Develop webservice in PHPDevelop webservice in PHP
Develop webservice in PHP
 
REST API Recommendations
REST API RecommendationsREST API Recommendations
REST API Recommendations
 
ASP.NET WEB API
ASP.NET WEB APIASP.NET WEB API
ASP.NET WEB API
 
RESTing with JAX-RS
RESTing with JAX-RSRESTing with JAX-RS
RESTing with JAX-RS
 
Introduction to RESTful Webservices in JAVA
Introduction to RESTful Webservices  in JAVA Introduction to RESTful Webservices  in JAVA
Introduction to RESTful Webservices in JAVA
 
RESTful http_patterns_antipatterns
RESTful http_patterns_antipatternsRESTful http_patterns_antipatterns
RESTful http_patterns_antipatterns
 
Java Web Programming [5/9] : EL, JSTL and Custom Tags
Java Web Programming [5/9] : EL, JSTL and Custom TagsJava Web Programming [5/9] : EL, JSTL and Custom Tags
Java Web Programming [5/9] : EL, JSTL and Custom Tags
 
Webservices
WebservicesWebservices
Webservices
 
RESTful services with JAXB and JPA
RESTful services with JAXB and JPARESTful services with JAXB and JPA
RESTful services with JAXB and JPA
 
Best Practice in API Design
Best Practice in API DesignBest Practice in API Design
Best Practice in API Design
 
Spring Web Service, Spring Integration and Spring Batch
Spring Web Service, Spring Integration and Spring BatchSpring Web Service, Spring Integration and Spring Batch
Spring Web Service, Spring Integration and Spring Batch
 
Ws rest
Ws restWs rest
Ws rest
 
Android App Development 06 : Network & Web Services
Android App Development 06 : Network & Web ServicesAndroid App Development 06 : Network & Web Services
Android App Development 06 : Network & Web Services
 

Destaque

Java Reflection Explained Simply
Java Reflection Explained SimplyJava Reflection Explained Simply
Java Reflection Explained Simply
Ciaran McHale
 
Google drive for nonprofits webinar
Google drive for nonprofits webinarGoogle drive for nonprofits webinar
Google drive for nonprofits webinar
Craig Grella
 
How To Embed SlideShare Shows Into WordPress.com
How To Embed SlideShare Shows Into WordPress.comHow To Embed SlideShare Shows Into WordPress.com
How To Embed SlideShare Shows Into WordPress.com
Kathy Gill
 

Destaque (18)

Java reflection
Java reflectionJava reflection
Java reflection
 
Java Reflection @KonaTechAdda
Java Reflection @KonaTechAddaJava Reflection @KonaTechAdda
Java Reflection @KonaTechAdda
 
Java Exploit Analysis .
Java Exploit Analysis .Java Exploit Analysis .
Java Exploit Analysis .
 
Java notes(OOP) jkuat IT esection
Java notes(OOP) jkuat IT esectionJava notes(OOP) jkuat IT esection
Java notes(OOP) jkuat IT esection
 
Reflection in Java
Reflection in JavaReflection in Java
Reflection in Java
 
Java Reflection Explained Simply
Java Reflection Explained SimplyJava Reflection Explained Simply
Java Reflection Explained Simply
 
Integrating Google APIs into Your Applications
Integrating Google APIs into Your ApplicationsIntegrating Google APIs into Your Applications
Integrating Google APIs into Your Applications
 
Image galley ppt
Image galley pptImage galley ppt
Image galley ppt
 
Image Optimization for the Web at php|works
Image Optimization for the Web at php|worksImage Optimization for the Web at php|works
Image Optimization for the Web at php|works
 
Google drive for nonprofits webinar
Google drive for nonprofits webinarGoogle drive for nonprofits webinar
Google drive for nonprofits webinar
 
PHP Project PPT
PHP Project PPTPHP Project PPT
PHP Project PPT
 
Php Presentation
Php PresentationPhp Presentation
Php Presentation
 
LinkedIn Learning | What We're Learning About Learning
LinkedIn Learning | What We're Learning About LearningLinkedIn Learning | What We're Learning About Learning
LinkedIn Learning | What We're Learning About Learning
 
How To Embed SlideShare Shows Into WordPress.com
How To Embed SlideShare Shows Into WordPress.comHow To Embed SlideShare Shows Into WordPress.com
How To Embed SlideShare Shows Into WordPress.com
 
How to prepare for a long distance hiking trip
How to prepare for a long distance hiking tripHow to prepare for a long distance hiking trip
How to prepare for a long distance hiking trip
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
 
State of the Word 2011
State of the Word 2011State of the Word 2011
State of the Word 2011
 
Build Features, Not Apps
Build Features, Not AppsBuild Features, Not Apps
Build Features, Not Apps
 

Semelhante a Easy rest service using PHP reflection api

Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)
Fabien Potencier
 
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf Conference
 
Object Oriented Programming with PHP 5 - More OOP
Object Oriented Programming with PHP 5 - More OOPObject Oriented Programming with PHP 5 - More OOP
Object Oriented Programming with PHP 5 - More OOP
Wildan Maulana
 
PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overview
jsmith92
 
Django Class-based views (Slovenian)
Django Class-based views (Slovenian)Django Class-based views (Slovenian)
Django Class-based views (Slovenian)
Luka Zakrajšek
 

Semelhante a Easy rest service using PHP reflection api (20)

Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
 
WordPress REST API hacking
WordPress REST API hackingWordPress REST API hacking
WordPress REST API hacking
 
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From Iusethis
 
Object Oriented Programming with PHP 5 - More OOP
Object Oriented Programming with PHP 5 - More OOPObject Oriented Programming with PHP 5 - More OOP
Object Oriented Programming with PHP 5 - More OOP
 
Как получить чёрный пояс по WordPress? v2.0
Как получить чёрный пояс по WordPress? v2.0Как получить чёрный пояс по WordPress? v2.0
Как получить чёрный пояс по WordPress? v2.0
 
Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5
 
Zend framework service
Zend framework serviceZend framework service
Zend framework service
 
Zend framework service
Zend framework serviceZend framework service
Zend framework service
 
Introduction to Zend Framework web services
Introduction to Zend Framework web servicesIntroduction to Zend Framework web services
Introduction to Zend Framework web services
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overview
 
Unit testing after Zend Framework 1.8
Unit testing after Zend Framework 1.8Unit testing after Zend Framework 1.8
Unit testing after Zend Framework 1.8
 
Codemotion appengine
Codemotion appengineCodemotion appengine
Codemotion appengine
 
Django Class-based views (Slovenian)
Django Class-based views (Slovenian)Django Class-based views (Slovenian)
Django Class-based views (Slovenian)
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony Techniques
 

Mais de Matthieu Aubry

Mais de Matthieu Aubry (17)

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

Último

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
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
vu2urc
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Último (20)

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
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
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
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
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
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
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
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)
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
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
 
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
 
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...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 

Easy rest service using PHP reflection api

  • 1. Easy Web Services using PHP reflection API phplondon, Dec 4 th 2008
  • 4.
  • 5.
  • 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: %s" ,  var_export ( $method -> getDocComment (),  1 ));
  • 8.
  • 9.
  • 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.
  • 19. ... and use the Proxy class to generate your API documentation (from the code, and by reverse engineering your method comments)
  • 21.