SlideShare une entreprise Scribd logo
1  sur  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]

Contenu connexe

Tendances

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
 

Tendances (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
 

En vedette

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
 

En vedette (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
 

Similaire à 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
 

Similaire à 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
 

Plus de 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
 

Plus 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
 

Dernier

Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 

Dernier (20)

Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 

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.