SlideShare a Scribd company logo
1 of 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]

More Related Content

What's hot

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 5Michael Girouard
 
RestFull Webservices with JAX-RS
RestFull Webservices with JAX-RSRestFull Webservices with JAX-RS
RestFull Webservices with JAX-RSNeil Ghosh
 
Consuming RESTful services in PHP
Consuming RESTful services in PHPConsuming RESTful services in PHP
Consuming RESTful services in PHPZoran Jeremic
 
Developing RESTful WebServices using Jersey
Developing RESTful WebServices using JerseyDeveloping RESTful WebServices using Jersey
Developing RESTful WebServices using Jerseyb_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-RSKatrien Verbert
 
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.0Dmytro Chyzhykov
 
REST API Recommendations
REST API RecommendationsREST API Recommendations
REST API RecommendationsJeelani Shaik
 
Introduction to RESTful Webservices in JAVA
Introduction to RESTful Webservices  in JAVA Introduction to RESTful Webservices  in JAVA
Introduction to RESTful Webservices in JAVA psrpatnaik
 
RESTful http_patterns_antipatterns
RESTful http_patterns_antipatternsRESTful http_patterns_antipatterns
RESTful http_patterns_antipatternsJan Algermissen
 
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 TagsIMC Institute
 
Webservices
WebservicesWebservices
Webservicess4al_com
 
RESTful services with JAXB and JPA
RESTful services with JAXB and JPARESTful services with JAXB and JPA
RESTful services with JAXB and JPAShaun Smith
 
Best Practice in API Design
Best Practice in API DesignBest Practice in API Design
Best Practice in API DesignLorna Mitchell
 
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 BatchEberhard Wolff
 
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 ServicesAnuchit Chalothorn
 

What's hot (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
 

Viewers also liked

Java Exploit Analysis .
Java Exploit Analysis .Java Exploit Analysis .
Java Exploit Analysis .Rahul Sasi
 
Java Reflection Explained Simply
Java Reflection Explained SimplyJava Reflection Explained Simply
Java Reflection Explained SimplyCiaran McHale
 
Integrating Google APIs into Your Applications
Integrating Google APIs into Your ApplicationsIntegrating Google APIs into Your Applications
Integrating Google APIs into Your ApplicationsChris Schalk
 
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|worksStoyan Stefanov
 
Google drive for nonprofits webinar
Google drive for nonprofits webinarGoogle drive for nonprofits webinar
Google drive for nonprofits webinarCraig Grella
 
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 LearningLinkedIn Learning Solutions
 
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.comKathy Gill
 
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 tripAustin Gratham
 
State of the Word 2011
State of the Word 2011State of the Word 2011
State of the Word 2011photomatt
 

Viewers also liked (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
 

Similar to 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
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For BeginnersJonathan Wage
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologyDaniel Knell
 
WordPress REST API hacking
WordPress REST API hackingWordPress REST API hacking
WordPress REST API hackingJeroen van Dijk
 
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
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From IusethisMarcus Ramberg
 
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 OOPWildan Maulana
 
Как получить чёрный пояс по WordPress? v2.0
Как получить чёрный пояс по WordPress? v2.0Как получить чёрный пояс по WordPress? v2.0
Как получить чёрный пояс по WordPress? v2.0Yevhen Kotelnytskyi
 
Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Elena Kolevska
 
Introduction to Zend Framework web services
Introduction to Zend Framework web servicesIntroduction to Zend Framework web services
Introduction to Zend Framework web servicesMichelangelo van Dam
 
PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overviewjsmith92
 
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.8Michelangelo van Dam
 
Django Class-based views (Slovenian)
Django Class-based views (Slovenian)Django Class-based views (Slovenian)
Django Class-based views (Slovenian)Luka Zakrajšek
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐいHisateru Tanaka
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony TechniquesKris Wallsmith
 

Similar to 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
 

More from Matthieu Aubry

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 meetupMatthieu Aubry
 
Introduction to piwik analytics platform 2015
Introduction to piwik analytics platform 2015Introduction to piwik analytics platform 2015
Introduction to piwik analytics platform 2015Matthieu Aubry
 
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 futureMatthieu Aubry
 
Web Analytics for your ePortfolio
Web Analytics for your ePortfolioWeb Analytics for your ePortfolio
Web Analytics for your ePortfolioMatthieu Aubry
 
Intro to Piwik project - 2014
Intro to Piwik project - 2014Intro to Piwik project - 2014
Intro to Piwik project - 2014Matthieu Aubry
 
Piwik at INTEROP TOKYO, June 2013
Piwik at INTEROP TOKYO, June 2013Piwik at INTEROP TOKYO, June 2013
Piwik at INTEROP TOKYO, June 2013Matthieu Aubry
 
Piwik Analytics - Marketing Brochure
Piwik Analytics - Marketing BrochurePiwik Analytics - Marketing Brochure
Piwik Analytics - Marketing BrochureMatthieu Aubry
 
Piwik in Japan Osc2013 photo
Piwik in Japan Osc2013 photoPiwik in Japan Osc2013 photo
Piwik in Japan Osc2013 photoMatthieu Aubry
 
Piwik オープンソースウェブ解析 2011年資料 - Piwik Restrospective
Piwik オープンソースウェブ解析  2011年資料 - Piwik RestrospectivePiwik オープンソースウェブ解析  2011年資料 - Piwik Restrospective
Piwik オープンソースウェブ解析 2011年資料 - Piwik RestrospectiveMatthieu Aubry
 
Piwik Japan - interrop2012 in tokyo
Piwik Japan - interrop2012 in tokyoPiwik Japan - interrop2012 in tokyo
Piwik Japan - interrop2012 in tokyoMatthieu Aubry
 
Piwik presentation 2011
Piwik presentation 2011Piwik presentation 2011
Piwik presentation 2011Matthieu Aubry
 
Piwik Retrospective 2008
Piwik Retrospective 2008Piwik Retrospective 2008
Piwik Retrospective 2008Matthieu Aubry
 
Piwik - open source web analytics
Piwik - open source web analyticsPiwik - open source web analytics
Piwik - open source web analyticsMatthieu Aubry
 
Piwik - build a developer community
Piwik - build a developer communityPiwik - build a developer community
Piwik - build a developer communityMatthieu Aubry
 
Dashboard - definition, examples
Dashboard - definition, examplesDashboard - definition, examples
Dashboard - definition, examplesMatthieu Aubry
 

More from 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
 

Recently uploaded

TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
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...Miguel Araújo
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
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
 
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
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
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
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
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
 
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
 
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 Servicegiselly40
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
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 productivityPrincipled Technologies
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
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
 
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
 

Recently uploaded (20)

TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
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...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
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
 
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...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
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
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
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
 
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)
 
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
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
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
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
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
 
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
 

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.