SlideShare a Scribd company logo
Designing CakePHP plugins for consuming APIsBy @neilcrookes for CakeFest2010www.neilcrookes.comgithub.com/neilcrookes
ContentsFoundationsCakePHP plugins, APIs, REST, HTTP, CakePHP HttpSocket, OAuthDesign approachTraditional approach, issues with that, my solutionExamples
Types of CakePHP pluginsMini appsProvide full functionality you can include in your app e.g. blog, store locatorExtendersExtend your app with more functionality e.g. commentable & taggableEnhancersEnhance your apps existing functionality e.g. filterWrappersProvide functionality to access 3rd party APIs
APIsSource: http://www.programmableweb.com/apis 73%  of all APIs (listed on ProgrammableWeb) are RESTful

Recommended for you

Slim Framework
Slim FrameworkSlim Framework
Slim Framework

The document discusses the Slim microframework for PHP. It provides an overview of Slim, describing how it is used to quickly write REST APIs. It covers installing Slim, using the Application class as the entry point, and handling requests and responses. Key aspects covered include registering routes, accessing request headers and body, setting response status and headers, and returning JSON responses.

how to write rest api using slim frameworkrest vs soapphp rest api framework
Web api
Web apiWeb api
Web api

ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.

web apiudai talksrest
XamarinとAWSをつないでみた話
XamarinとAWSをつないでみた話XamarinとAWSをつないでみた話
XamarinとAWSをつないでみた話

The document contains information about OpenAPI/Swagger including: - Members of the OpenAPI initiative including organizations from Oregon, São Paulo, and Frankfurt. - Details about the Swagger specification and examples of using Swagger code generation to generate API client code in C# from a Swagger specification. The generated code includes models, API interfaces, and an API client to call the API.

swaggerawsxamarin
My work so far has been mainly consuming RESTful APIs so this presentation and examples will focus on REST
But concepts illustrated in the design approach section later on can be applied to any protocolQuick intro to RESTREspresentational State Transfer“The largest known implementation of a system conforming to the REST architectural style is…” http://en.wikipedia.org/wiki/Representational_State_TransferThe World Wide WebClients and servers communicating via HTTPUses existing HTTP verbs (GET, POST etc)Acts on a resource (URI)
HTTPSend request<HTTP verb> <URI> HTTP/1.1<Header 1 name>: <Header 1 value>...<optional body>You’ll get some kind of response (hopefully)HTTP/1.1 <Status Code> <Status Message><Header 1 name>: <Header 1 value>...<optional body>
Simple HTTP GET Request & ResponseRequestGET http://www.example.com/index.html HTTP/1.1User-Agent: My Web BrowserResponseHTTP/1.1 200 OKContent-Type: text/htmlContent-Length: 70<html><head><title>My Web Page</title></head><body><h1>My Web Page</h1></body></html>

Recommended for you

6 introduction-php-mvc-cakephp-m6-views-slides
6 introduction-php-mvc-cakephp-m6-views-slides6 introduction-php-mvc-cakephp-m6-views-slides
6 introduction-php-mvc-cakephp-m6-views-slides

The document provides an overview of the CakePHP view layer and its components. It discusses the presentation layer, template files, layouts, views, elements, helpers, and specific helpers like HtmlHelper and FormHelper. The view layer consists of layouts, views, elements, and helpers. Layouts wrap around views and contain common site elements. Views display unique content for each page. Elements contain reusable code snippets. Helpers provide logic and help generate forms, pagination, and other common code.

Request dispacther interface ppt
Request dispacther interface pptRequest dispacther interface ppt
Request dispacther interface ppt

The RequestDispatcher interface in Java allows servlets to dispatch or forward requests to other resources on the server like HTML files, JSP pages, or other servlets. It provides two main methods - forward() to forward a request and include() to include the response of a resource in the current response. The getRequestDispatcher() method of the ServletRequest interface returns a RequestDispatcher object that can then be used to call the forward() or include() methods, passing the request and response objects. An example is provided of a login servlet that uses RequestDispatcher to forward successfully authenticated requests to a welcome servlet or include an error message on failed authentication.

connectivityconnectionreport
Codeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept ImplementationCodeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept Implementation

This document describes implementing a two-step view concept in CodeIgniter by using output buffering. It involves three main components: 1) an initialization hook to start output buffering, 2) a helper to generate the two-step view content and load it into a layout view, and 3) a layout view to echo the content. The helper gets the buffered content, loads a view to generate the content string, loads the layout view and passes the content, and the layout view echoes the content within the HTML structure. This allows separating view generation and rendering for a cleaner separation of logic and presentation.

layoutcodeignitertwo step view
Simple HTTP POST Request & ResponseRequestPOST http://www.example.com/login HTTP/1.1Content-Type: application/x-www-form-urlencodedContent-Length: 38username=neilcrookes&password=abcd1234ResponseHTTP/1.1 301 Moved PermanentlyLocation: http://www.example.com/my_account
CakePHP’s HttpSocket Classcake/libs/http_socket.phpUsage:    App::import(‘Core’, ‘HttpSocket’);    $Http = new HttpSocket();    $response = $Http->request(array(    ‘method’ => ‘POST’,      ‘uri’ => array(        ‘host’ => ‘example.com’,        ‘path’ => ‘login’),      ‘body’ => array(        ‘username’ => ‘neilcrookes’,        ‘password’ => ‘abcd1234’)));See HttpSocket::request property for defaults HttpSocketHandles creating, writing to and reading from sockets (because it extends CakeSocket)Constructs HTTP escaped, encoded requests from array parameters you send itParses HTTP response from the server intoStatusBodyCookiesCan handle Basic Auth (username:password@)
OAuthIn summary, it allows users of a service (e.g. Twitter) to authorize other parties (i.e. your application) access to their accounts on that service, without sharing their password with the other parties.In reality, it means:a little bit of handshaking between your app and the service provider to get various string tokensredirecting the user to the service in order for them to authorize your app to access their account, so the user only signs in to the service, not your app.the service provides you with a token you can persist and use to make authorized requests to their service on behalf of the userIn practice it’s just an extra header line (Authorization header) in the HTTP request which containssome arbitrary parameters e.g. timestampa token that identifies your application to the API providera signature string that signs the request and is a hash of various request parameters and the secret tokens you retrieved aboveUsed by e.g. Twitter & Google APIs
HttpSocketOauthUsage example to tweet “Hello world!”:App::import('Vendor', 'HttpSocketOauth');$Http = new HttpSocketOauth();$response = $Http->request(array(  'method' => 'POST',  'uri' => array(    'host' => 'api.twitter.com',    'path' => '1/statuses/update.json'),  'auth' => array(    'method' => 'OAuth',    'oauth_token' => <oauth token>,    'oauth_token_secret' => <oauth token secret>,   'oauth_consumer_key' => <oauth consumer key>,    'oauth_consumer_secret' => <oauth consumer secret>),  'body' => array(    'status' => 'Hello world!')));http://www.neilcrookes.com/2010/04/12/cakephp-oauth-extension-to-httpsocket/http://github.com/neilcrookes/http_socket_oauth

Recommended for you

Using the new WordPress REST API
Using the new WordPress REST APIUsing the new WordPress REST API
Using the new WordPress REST API

This document discusses the WordPress REST API, which allows consuming and modifying WordPress data via a standards-compliant JSON REST API from within WordPress or another application. It provides examples of using the API to get posts, parse responses with Handlebars, and build a JavaScript client. The REST API offers advantages like decoupling the front-end from WordPress, and allows any front-end developer to work on a WordPress-powered site. It is currently a plugin but will be included in WordPress core.

Day01 api
Day01   apiDay01   api
Day01 api

This document outlines a course on PHP web services. It covers connecting to remote web services using CURL and Guzzle, creating REST and SOAP APIs, and consuming web services. The introduction defines web services and common types like SOAP and REST. Part 1 discusses JSON and encoding/decoding data. Part 2 focuses on connecting to external APIs using CURL and handling errors.

apiweb servicesphp
Building RESTful applications using Spring MVC
Building RESTful applications using Spring MVCBuilding RESTful applications using Spring MVC
Building RESTful applications using Spring MVC

REST is an alternate and simpler approach for implementing WebServices. It is based on the HTTP protocol and hence leverages a lot of existing infrastructures. It uses an uniform interface thus making it easy to build client applications. In this session we will look at the fundamental concepts behind REST (Resource, URI, Stateless Conversation ..) and how to apply it in the context of a real applcation. We will also discuss the pros & cons of RESTful vs Soap based webservices. We will discuss the design of RESTful application and then look at how to implement it using Spring MVC.

indiajavaindicthreads
ContentsFoundationsCakePHP plugins, APIs, REST, HTTP, CakePHP HttpSocket, OAuthDesign approachTraditional approach, issues with that, my solutionExamples
Traditional approach: DataSourceComplex DataSource containing all the logicCall methods on the DataSource directly from your models or controllersor as implied by the example Twitter DataSource in the cook book: access DataSource methods through your models but include most of the logic in the DataSourcehttp://book.cakephp.org/view/1077/An-ExampleWorks well for simple stuffThis is how I started implementing
However...Does not scale well for large APIsTwitter has ~100 API calls available, all with a wide variety of options and parameters. The cook book Twitter DataSource partially implements 2 API calls and is 86 linesDoes not exploit built-in CakePHP goodnessCallbacksValidationPaginationDoes not allow for multiple models (and therefore  multiple schemas) to use the same DataSourceDidn’t feel right to me
So what does feel right?What operations are we actually doing?Reading dataCreating and updating dataDeleting datai.e. Find, save & deleteWhat type of classes in CakePHP provide these methods?

Recommended for you

Building Applications Using Ajax
Building Applications Using AjaxBuilding Applications Using Ajax
Building Applications Using Ajax

The first of its kind Web Technology Conference on Open Source Technology, WebOSS '07 was organised in Kolkata on Sat, 13th Oct 07 and I spoke at the event as one of the participants on "Building Applications using AJAX". Here I will share my presentation.

An introduction to Laravel Passport
An introduction to Laravel PassportAn introduction to Laravel Passport
An introduction to Laravel Passport

Introduction to Laravel Passport - the oAuth 2 server for Laravel, presented at the PHP North East user group, PHPNE, in September 2016.

oauthphpnelaravel
Rails 3 Beautiful Code
Rails 3 Beautiful CodeRails 3 Beautiful Code
Rails 3 Beautiful Code

On February 18th, 2010 was O'Reilly's "Exploring Rails 3" online conference and these are Gregg Pollack's slides. They are by no means a complete record of improvements in Rails 3, but they should serve to get your appetite wet.

rails 3railsruby on rails
ModelsPhoto by memoflores, available under creative commonshttp://www.flickr.com/photos/memoflores/And what should models be?...
FAT!Photo by cstreetus, available under creative commonshttp://www.flickr.com/photos/cstreetus/Sorry but every other image I found through searching for “fat models” or “fat ladies” was completely inappropriate ;-)
So if we move our API calls into Model::find(), Model::save() and Model::delete() methodsIt feels like the right placeWe’re more familiar with interacting with theseWe can have lots of simple models classes to achieve scale, separation of concerns and different models can have different validation rules and schemas and we can collect them together in a pluginBut...
But what about CakePHP goodness?Triggering callbacksbeforeFind(), afterFind(), beforeSave(), afterSave(), beforeValidate(), beforeDelete(), afterDelete()Triggering validationHandling custom find typesIf we made the API calls directly in these methods and returned the response, to exploit this excellent built-in additional CakePHP functionality we’d have to trigger/code them manuallyWe’d be duplicating loads of code from CakePHP’s core Model class.Not very DRY

Recommended for you

Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram VaswaniCreating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani

Explains how to use the Slim PHP micro-framework to quickly deploy a REST API. Includes sample code to implement common API requirements, such as authentication, request logging and multi-format support.

restphpmicro-framework
Spring Mvc Rest
Spring Mvc RestSpring Mvc Rest
Spring Mvc Rest

The document discusses building RESTful applications with Spring MVC. It covers the pillars of REST including resources, URIs, HTTP methods, and representations. It provides examples of modeling resources as controllers and mapping HTTP methods to controller actions. It also discusses content negotiation, supporting different data representations like JSON, XML and RSS using Spring views.

Zend framework
Zend frameworkZend framework
Zend framework

Zend Framework is a PHP web application framework that uses a model-view-controller (MVC) architecture. It provides modules for common tasks like database access and Google APIs. The framework encourages separating code into models, views, and controllers. It also includes tools for creating projects, actions, forms and connecting to databases to build full-featured web applications.

frameworkphpzend
To understand the solution, we must understand CakePHP Model internalsModel methods like find(), save() and delete() accept various params such as conditions, data to save etcHandle custom find types for find() onlyHandle validation for save() onlyTrigger the before*() callbacksCall create(), read(), update() or delete() on that model’s DataSourceTrigger the after*() callbacksReturn the result
So what’s my solution for designing CakePHP plugins for consuming APIs?Plugin containing one model for each type of resource in the API e.g. TwitterStatus or YouTubeVideoModels implement find() (or actually more commonly just CakePHP custom find types), save() and delete() methods as appropriateThese methods set the details of the request, i.e. The array that represents an HTTP request that HttpSocket::request() methods expects (as we saw earlier in this presentation) in a request property of your model, then calls the same method on the parent object i.e. Model.Cont...
Solution continuedCakePHP Model class handles validation and custom find types, triggers callbacks etc then calls create(), read(), update() or delete() on the child model’s (your model’s) DataSource, and passes the model objectYour model’s useDbConfig property should be set to a custom DataSource that you also include in your pluginYour DataSource implements the appropriate CRUD method(s) and issues the API call described in the model’s requestproperty, and returns the results
Hmmm, sounds complicatedIt’s notI’ve written a REST DataSource you can use (see later)All you have to do is create a model that has find() or save() methods, in which you set a request property to an array expected by HttpSocket::request() and call the same method on the parent.

Recommended for you

Single Page Web Apps As WordPress Admin Interfaces Using AngularJS & The Word...
Single Page Web Apps As WordPress Admin Interfaces Using AngularJS & The Word...Single Page Web Apps As WordPress Admin Interfaces Using AngularJS & The Word...
Single Page Web Apps As WordPress Admin Interfaces Using AngularJS & The Word...

This document discusses using AngularJS to build single page applications for WordPress admin interfaces that use the WordPress REST API. It covers why this approach is beneficial, how to set it up using Angular routing, controllers, factories and HTTP requests to interact with the REST API. Benefits mentioned include making WordPress interfaces more modern and dynamic, empowering others to build plugins in a decentralized way, and the ease of transitioning to software as a service models. The document encourages readers to learn Angular and check out additional resources on the topic.

wordpressangularjavascript
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overview

Rails 3 provides a concise overview of changes in Rails 3 including maintaining MVC structure and RESTful routing while improving areas like file structure, block helpers, routing and constraints, ActiveRecord querying, resources routing, and ActionMailer delivery. Key changes include a more Rack-like implementation, chainable ActiveRecord scopes, and pagination and layout support in ActionMailer.

rails3posscon
Practical catalyst
Practical catalystPractical catalyst
Practical catalyst

Catalyst is a web framework for Perl that allows developers to build dynamic web applications in a modular, reusable way. It utilizes common Perl techniques like Moose, DBIx::Class and Template Toolkit to handle tasks like object modeling, database access and view rendering. Catalyst applications can be built in a model-view-controller style to separate application logic, data access and presentation layers. This framework provides a standard way to write reusable code and build web UIs for tasks like system administration and automation.

ajaxperljson
E.g. Creating a tweet<?phpclass TwitterStatus extends AppModel {  public function save($data = null) {    $this->request = array(      'uri' => array(        'host' => 'api.twitter.com',        'path' => '1/statuses/update.json'),      'body' => array(        'status' => $data['TwitterStatus']['text']));    return parent::save($data);  }}?>
Which you call like thisClassRegistry::init('Twitter.TwitterStatus')->save(array(  'TwitterStatus' => array(    'text' => “Hello world!”)));... from anywhere you like in your CakePHP application, e.g. In your Post model afterSave() method, thus automatically creating a tweet every time you create a new post.
RestSourcehttp://www.neilcrookes.com/2010/06/01/rest-datasource-plugin-for-cakephp/http://github.com/neilcrookes/CakePHP-ReST-DataSource-PluginYou can set your model’s useDbConfigparam to this DataSource, or you can write your own DataSource that extends this oneE.g. Override RestSource::request() to add in the host key in the $model->request property if it’s the same for all API calls, then call parent::(request)
This diagram illustrates the flow through the methods an classes involved in creating a tweethttps://docs.google.com/drawings/edit?id=1Aht7huICl9bhl2hWRdM0VdoaBePpJ0kXkceyQpAR8os&hl=en_GB&authkey=CISSqJkN

Recommended for you

En story of cakephp2.0
En story of cakephp2.0En story of cakephp2.0
En story of cakephp2.0

CakePHP 2.0 introduces major enhancements such as decoupling request and response handling, separating authentication logic into its own class, and allowing dynamic loading of components, helpers and behaviors through a new ObjectCollection class. It also resolves various issues like improving security, making pagination support GET requests, and allowing more flexible routes. The new version aims to improve decoupling, flexibility and performance while maintaining backwards compatibility.

Implementing Comet using PHP
Implementing Comet using PHPImplementing Comet using PHP
Implementing Comet using PHP

This talk was given at the Dutch PHP Conference 2011 and details the use of Comet (aka reverse ajax or ajax push) technologies and the importance of websockets and server-sent events. More information is available at http://joind.in/3237.

king foodpc11php
Manish
ManishManish
Manish

Cookies and sessions allow storing and retrieving data across multiple requests in PHP. Cookies are stored on the client side while sessions are stored on the server side. Cookies are created using the setcookie() function and retrieved using the $_COOKIE superglobal array. Sessions are created using the session_start() function and data is stored in the $_SESSION superglobal array. Both cookies and sessions can be deleted by unset() or by letting them expire.

In summaryBy designing plugins like this you’re providingSimple (1 line) method calls to API functionsThat are familiar to all CakePHP bakersAnd easy to documentYou also get to exploit CakePHP goodness such as validation and callbacks etcYou can have multiple models, one for each resource type on the API, each with it’s own schema (which the FormHelper uses) and validation rules
ContentsFoundationsCakePHP plugins, APIs, REST, HTTP, CakePHP HttpSocket, OAuthDesign approachTraditional approach, issues with that, my solutionExamples
ExamplesYouTubeTwitter
Uploading a YouTube Video – you doClassRegistry::init('Gdata.YouTubeVideo')->save(array(  'YouTubeVideo' => array(    'title' => 'Flying into Chicago Airport',    'description' => 'Filmed through the plane window coming in over the lake',    'category' => 'Travel',    'keywords' => 'Chicago, Plane, Lake, Skyline',    'rate' => 'allowed',    'comment' => 'allowed',    'commentVote' => 'allowed',    'videoRespond' => 'allowed',    'embed' => 'allowed',    'syndicate' => 'allowed',    'private' => 1,    'file' => array(      'name' => 'chicago 1 060.AVI',      'type' => 'video/avi',      'tmp_name' => 'C:indowsemphp6D66.tmp',      'error' => 0,      'size' => 5863102))));

Recommended for you

Php
PhpPhp
Php

PHP is a server-side scripting language used for web development. It allows developers to embed PHP code into HTML pages which is executed on the server to produce dynamic web pages. Some key points about PHP include: - It is free, open source, and runs on many platforms including Windows and Linux. - PHP code is easy to embed into HTML and syntax uses opening and closing tags. - It can be used to connect to databases like MySQL and Oracle to dynamically display data on web pages. - Common PHP functions include echo to output content, if statements for conditional logic, and arrays to store multiple values. - Cookies can be used to store and retrieve data on the client-side browser to

ASP.NET MVC introduction
ASP.NET MVC introductionASP.NET MVC introduction
ASP.NET MVC introduction

The document provides an introduction and overview of ASP.NET MVC, covering topics such as routing, controllers, actions, views, and passing data between controllers and views. It compares ASP.NET MVC to traditional ASP.NET WebForms, outlines the MVC architecture and project structure, and describes how routing maps URLs to controller actions. Key aspects of controllers, views, partial views, HTML helpers, and view engines are also summarized.

asp.netmvcweb development
CGI Presentation
CGI PresentationCGI Presentation
CGI Presentation

The document provides an overview of CGI (Common Gateway Interface) and how it enables dynamic web content. It discusses how CGI works, alternatives like PHP and Java servlets, configuring Apache web server for CGI, programming CGI applications using Perl and the CGI.pm module, handling input/output and errors. It also includes an example CGI application in Perl for counting button clicks using sessions and cookies to manage state.

Uploading a YouTube Video – plugin createsPOST /feeds/api/users/default/uploads HTTP/1.1Host: uploads.gdata.youtube.comConnection: closeUser-Agent: CakePHPContent-Type: multipart/related; boundary="Next_Part_4c801b22-52e8-4c70-961b-0534fba3b5b1“Slug: chicago 1 060.AVIGdata-Version: 2X-Gdata-Key: key=<my developer key>Authorization: OAuth oauth_version="1.0",oauth_signature_method="HMAC-SHA1",oauth_consumer_key="anonymous",oauth_token=“<my oauth token>",oauth_nonce="fa4b6fc350e19f675f2e5660657e643c",oauth_timestamp="1283463971",oauth_signature="3fIXJ%2BmdV6KLk4zJYszR7M90lIg%3D“Content-Length: 5864289--Next_Part_4c801b22-52e8-4c70-961b-0534fba3b5b1Content-Type: application/atom+xml; charset=UTF-8<?xml version="1.0" encoding="utf-8"?><entry xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" xmlns:yt="http://gdata.youtube.com/schemas/2007">  <media:group>    <media:title type="plain">Flying into Chicago Airport</media:title>    <media:description type="plain">Filmed through the plane window, shows coming in over the lake</media:description>    <media:category scheme="http://gdata.youtube.com/schemas/2007/categories.cat">Travel</media:category>    <media:keywords>Chicago, Plane, Lake, Skyline</media:keywords>    <yt:private/>  </media:group>  <yt:accessControl action="rate" permission="allowed"/>  <yt:accessControl action="comment" permission="allowed"/>  <yt:accessControl action="commentVote" permission="allowed"/><  <yt:accessControl action="videoRespond" permission="allowed"/>  <yt:accessControl action="embed" permission="allowed"/>  <yt:accessControl action="syndicate" permission="allowed"/></entry> --Next_Part_4c801b22-52e8-4c70-961b-0534fba3b5b1 Content-Type: video/aviContent-Transfer-Encoding: binary<binary file data>

More Related Content

What's hot

4 introduction-php-mvc-cakephp-m4-controllers-slides
4 introduction-php-mvc-cakephp-m4-controllers-slides4 introduction-php-mvc-cakephp-m4-controllers-slides
4 introduction-php-mvc-cakephp-m4-controllers-slides
MasterCode.vn
 
REST API Laravel
REST API LaravelREST API Laravel
REST API Laravel
John Dave Decano
 
ACL in CodeIgniter
ACL in CodeIgniterACL in CodeIgniter
ACL in CodeIgniter
mirahman
 
Slim Framework
Slim FrameworkSlim Framework
Slim Framework
Pramod Raghav
 
Web api
Web apiWeb api
Web api
udaiappa
 
XamarinとAWSをつないでみた話
XamarinとAWSをつないでみた話XamarinとAWSをつないでみた話
XamarinとAWSをつないでみた話
Takehito Tanabe
 
6 introduction-php-mvc-cakephp-m6-views-slides
6 introduction-php-mvc-cakephp-m6-views-slides6 introduction-php-mvc-cakephp-m6-views-slides
6 introduction-php-mvc-cakephp-m6-views-slides
MasterCode.vn
 
Request dispacther interface ppt
Request dispacther interface pptRequest dispacther interface ppt
Request dispacther interface ppt
Taha Malampatti
 
Codeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept ImplementationCodeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept Implementation
Abdul Malik Ikhsan
 
Using the new WordPress REST API
Using the new WordPress REST APIUsing the new WordPress REST API
Using the new WordPress REST API
Caldera Labs
 
Day01 api
Day01   apiDay01   api
Building RESTful applications using Spring MVC
Building RESTful applications using Spring MVCBuilding RESTful applications using Spring MVC
Building RESTful applications using Spring MVC
IndicThreads
 
Building Applications Using Ajax
Building Applications Using AjaxBuilding Applications Using Ajax
Building Applications Using Ajax
s_pradeep
 
An introduction to Laravel Passport
An introduction to Laravel PassportAn introduction to Laravel Passport
An introduction to Laravel Passport
Michael Peacock
 
Rails 3 Beautiful Code
Rails 3 Beautiful CodeRails 3 Beautiful Code
Rails 3 Beautiful Code
GreggPollack
 
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram VaswaniCreating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
vvaswani
 
Spring Mvc Rest
Spring Mvc RestSpring Mvc Rest
Spring Mvc Rest
Craig Walls
 
Zend framework
Zend frameworkZend framework
Zend framework
Prem Shankar
 
Single Page Web Apps As WordPress Admin Interfaces Using AngularJS & The Word...
Single Page Web Apps As WordPress Admin Interfaces Using AngularJS & The Word...Single Page Web Apps As WordPress Admin Interfaces Using AngularJS & The Word...
Single Page Web Apps As WordPress Admin Interfaces Using AngularJS & The Word...
Caldera Labs
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overview
Yehuda Katz
 

What's hot (20)

4 introduction-php-mvc-cakephp-m4-controllers-slides
4 introduction-php-mvc-cakephp-m4-controllers-slides4 introduction-php-mvc-cakephp-m4-controllers-slides
4 introduction-php-mvc-cakephp-m4-controllers-slides
 
REST API Laravel
REST API LaravelREST API Laravel
REST API Laravel
 
ACL in CodeIgniter
ACL in CodeIgniterACL in CodeIgniter
ACL in CodeIgniter
 
Slim Framework
Slim FrameworkSlim Framework
Slim Framework
 
Web api
Web apiWeb api
Web api
 
XamarinとAWSをつないでみた話
XamarinとAWSをつないでみた話XamarinとAWSをつないでみた話
XamarinとAWSをつないでみた話
 
6 introduction-php-mvc-cakephp-m6-views-slides
6 introduction-php-mvc-cakephp-m6-views-slides6 introduction-php-mvc-cakephp-m6-views-slides
6 introduction-php-mvc-cakephp-m6-views-slides
 
Request dispacther interface ppt
Request dispacther interface pptRequest dispacther interface ppt
Request dispacther interface ppt
 
Codeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept ImplementationCodeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept Implementation
 
Using the new WordPress REST API
Using the new WordPress REST APIUsing the new WordPress REST API
Using the new WordPress REST API
 
Day01 api
Day01   apiDay01   api
Day01 api
 
Building RESTful applications using Spring MVC
Building RESTful applications using Spring MVCBuilding RESTful applications using Spring MVC
Building RESTful applications using Spring MVC
 
Building Applications Using Ajax
Building Applications Using AjaxBuilding Applications Using Ajax
Building Applications Using Ajax
 
An introduction to Laravel Passport
An introduction to Laravel PassportAn introduction to Laravel Passport
An introduction to Laravel Passport
 
Rails 3 Beautiful Code
Rails 3 Beautiful CodeRails 3 Beautiful Code
Rails 3 Beautiful Code
 
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram VaswaniCreating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
 
Spring Mvc Rest
Spring Mvc RestSpring Mvc Rest
Spring Mvc Rest
 
Zend framework
Zend frameworkZend framework
Zend framework
 
Single Page Web Apps As WordPress Admin Interfaces Using AngularJS & The Word...
Single Page Web Apps As WordPress Admin Interfaces Using AngularJS & The Word...Single Page Web Apps As WordPress Admin Interfaces Using AngularJS & The Word...
Single Page Web Apps As WordPress Admin Interfaces Using AngularJS & The Word...
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overview
 

Similar to Designing CakePHP plugins for consuming APIs

Practical catalyst
Practical catalystPractical catalyst
Practical catalyst
dwm042
 
En story of cakephp2.0
En story of cakephp2.0En story of cakephp2.0
En story of cakephp2.0
Hiroki Shimizu
 
Implementing Comet using PHP
Implementing Comet using PHPImplementing Comet using PHP
Implementing Comet using PHP
King Foo
 
Manish
ManishManish
Manish
Manish Jain
 
Php
PhpPhp
ASP.NET MVC introduction
ASP.NET MVC introductionASP.NET MVC introduction
ASP.NET MVC introduction
Tomi Juhola
 
CGI Presentation
CGI PresentationCGI Presentation
CGI Presentation
Sopan Shewale
 
Php interview questions
Php interview questionsPhp interview questions
Php interview questions
sekar c
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's Code
Wildan Maulana
 
Webservices in SalesForce (part 1)
Webservices in SalesForce (part 1)Webservices in SalesForce (part 1)
Webservices in SalesForce (part 1)
Mindfire Solutions
 
OpenSocial Intro
OpenSocial IntroOpenSocial Intro
OpenSocial Intro
Pamela Fox
 
Php frameworks
Php frameworksPhp frameworks
Php frameworks
Anil Kumar Panigrahi
 
Compass Framework
Compass FrameworkCompass Framework
Compass Framework
Lukas Vlcek
 
Http programming in play
Http programming in playHttp programming in play
Http programming in play
Knoldus Inc.
 
RESTful SOA - 中科院暑期讲座
RESTful SOA - 中科院暑期讲座RESTful SOA - 中科院暑期讲座
RESTful SOA - 中科院暑期讲座
Li Yi
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
BG Java EE Course
 
Create a web-app with Cgi Appplication
Create a web-app with Cgi AppplicationCreate a web-app with Cgi Appplication
Create a web-app with Cgi Appplication
olegmmiller
 
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
Guillaume Laforge
 
Intro To Mvc Development In Php
Intro To Mvc Development In PhpIntro To Mvc Development In Php
Intro To Mvc Development In Php
funkatron
 
ActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group PresentationActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group Presentation
ipolevoy
 

Similar to Designing CakePHP plugins for consuming APIs (20)

Practical catalyst
Practical catalystPractical catalyst
Practical catalyst
 
En story of cakephp2.0
En story of cakephp2.0En story of cakephp2.0
En story of cakephp2.0
 
Implementing Comet using PHP
Implementing Comet using PHPImplementing Comet using PHP
Implementing Comet using PHP
 
Manish
ManishManish
Manish
 
Php
PhpPhp
Php
 
ASP.NET MVC introduction
ASP.NET MVC introductionASP.NET MVC introduction
ASP.NET MVC introduction
 
CGI Presentation
CGI PresentationCGI Presentation
CGI Presentation
 
Php interview questions
Php interview questionsPhp interview questions
Php interview questions
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's Code
 
Webservices in SalesForce (part 1)
Webservices in SalesForce (part 1)Webservices in SalesForce (part 1)
Webservices in SalesForce (part 1)
 
OpenSocial Intro
OpenSocial IntroOpenSocial Intro
OpenSocial Intro
 
Php frameworks
Php frameworksPhp frameworks
Php frameworks
 
Compass Framework
Compass FrameworkCompass Framework
Compass Framework
 
Http programming in play
Http programming in playHttp programming in play
Http programming in play
 
RESTful SOA - 中科院暑期讲座
RESTful SOA - 中科院暑期讲座RESTful SOA - 中科院暑期讲座
RESTful SOA - 中科院暑期讲座
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Create a web-app with Cgi Appplication
Create a web-app with Cgi AppplicationCreate a web-app with Cgi Appplication
Create a web-app with Cgi Appplication
 
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
 
Intro To Mvc Development In Php
Intro To Mvc Development In PhpIntro To Mvc Development In Php
Intro To Mvc Development In Php
 
ActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group PresentationActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group Presentation
 

Recently uploaded

find out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challengesfind out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challenges
huseindihon
 
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
Chris Swan
 
Cookies program to display the information though cookie creation
Cookies program to display the information though cookie creationCookies program to display the information though cookie creation
Cookies program to display the information though cookie creation
shanthidl1
 
20240702 Présentation Plateforme GenAI.pdf
20240702 Présentation Plateforme GenAI.pdf20240702 Présentation Plateforme GenAI.pdf
20240702 Présentation Plateforme GenAI.pdf
Sally Laouacheria
 
20240705 QFM024 Irresponsible AI Reading List June 2024
20240705 QFM024 Irresponsible AI Reading List June 202420240705 QFM024 Irresponsible AI Reading List June 2024
20240705 QFM024 Irresponsible AI Reading List June 2024
Matthew Sinclair
 
Pigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdfPigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdf
Pigging Solutions
 
UiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs ConferenceUiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs Conference
UiPathCommunity
 
The Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU CampusesThe Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU Campuses
Larry Smarr
 
INDIAN AIR FORCE FIGHTER PLANES LIST.pdf
INDIAN AIR FORCE FIGHTER PLANES LIST.pdfINDIAN AIR FORCE FIGHTER PLANES LIST.pdf
INDIAN AIR FORCE FIGHTER PLANES LIST.pdf
jackson110191
 
Recent Advancements in the NIST-JARVIS Infrastructure
Recent Advancements in the NIST-JARVIS InfrastructureRecent Advancements in the NIST-JARVIS Infrastructure
Recent Advancements in the NIST-JARVIS Infrastructure
KAMAL CHOUDHARY
 
How to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptxHow to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptx
Adam Dunkels
 
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALLBLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
Liveplex
 
DealBook of Ukraine: 2024 edition
DealBook of Ukraine: 2024 editionDealBook of Ukraine: 2024 edition
DealBook of Ukraine: 2024 edition
Yevgen Sysoyev
 
7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf
Enterprise Wired
 
The Rise of Supernetwork Data Intensive Computing
The Rise of Supernetwork Data Intensive ComputingThe Rise of Supernetwork Data Intensive Computing
The Rise of Supernetwork Data Intensive Computing
Larry Smarr
 
RPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptx
RPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptxRPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptx
RPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptx
SynapseIndia
 
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Bert Blevins
 
Comparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdfComparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdf
Andrey Yasko
 
Research Directions for Cross Reality Interfaces
Research Directions for Cross Reality InterfacesResearch Directions for Cross Reality Interfaces
Research Directions for Cross Reality Interfaces
Mark Billinghurst
 
Quantum Communications Q&A with Gemini LLM
Quantum Communications Q&A with Gemini LLMQuantum Communications Q&A with Gemini LLM
Quantum Communications Q&A with Gemini LLM
Vijayananda Mohire
 

Recently uploaded (20)

find out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challengesfind out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challenges
 
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
 
Cookies program to display the information though cookie creation
Cookies program to display the information though cookie creationCookies program to display the information though cookie creation
Cookies program to display the information though cookie creation
 
20240702 Présentation Plateforme GenAI.pdf
20240702 Présentation Plateforme GenAI.pdf20240702 Présentation Plateforme GenAI.pdf
20240702 Présentation Plateforme GenAI.pdf
 
20240705 QFM024 Irresponsible AI Reading List June 2024
20240705 QFM024 Irresponsible AI Reading List June 202420240705 QFM024 Irresponsible AI Reading List June 2024
20240705 QFM024 Irresponsible AI Reading List June 2024
 
Pigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdfPigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdf
 
UiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs ConferenceUiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs Conference
 
The Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU CampusesThe Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU Campuses
 
INDIAN AIR FORCE FIGHTER PLANES LIST.pdf
INDIAN AIR FORCE FIGHTER PLANES LIST.pdfINDIAN AIR FORCE FIGHTER PLANES LIST.pdf
INDIAN AIR FORCE FIGHTER PLANES LIST.pdf
 
Recent Advancements in the NIST-JARVIS Infrastructure
Recent Advancements in the NIST-JARVIS InfrastructureRecent Advancements in the NIST-JARVIS Infrastructure
Recent Advancements in the NIST-JARVIS Infrastructure
 
How to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptxHow to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptx
 
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALLBLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
 
DealBook of Ukraine: 2024 edition
DealBook of Ukraine: 2024 editionDealBook of Ukraine: 2024 edition
DealBook of Ukraine: 2024 edition
 
7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf
 
The Rise of Supernetwork Data Intensive Computing
The Rise of Supernetwork Data Intensive ComputingThe Rise of Supernetwork Data Intensive Computing
The Rise of Supernetwork Data Intensive Computing
 
RPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptx
RPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptxRPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptx
RPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptx
 
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
 
Comparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdfComparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdf
 
Research Directions for Cross Reality Interfaces
Research Directions for Cross Reality InterfacesResearch Directions for Cross Reality Interfaces
Research Directions for Cross Reality Interfaces
 
Quantum Communications Q&A with Gemini LLM
Quantum Communications Q&A with Gemini LLMQuantum Communications Q&A with Gemini LLM
Quantum Communications Q&A with Gemini LLM
 

Designing CakePHP plugins for consuming APIs

  • 1. Designing CakePHP plugins for consuming APIsBy @neilcrookes for CakeFest2010www.neilcrookes.comgithub.com/neilcrookes
  • 2. ContentsFoundationsCakePHP plugins, APIs, REST, HTTP, CakePHP HttpSocket, OAuthDesign approachTraditional approach, issues with that, my solutionExamples
  • 3. Types of CakePHP pluginsMini appsProvide full functionality you can include in your app e.g. blog, store locatorExtendersExtend your app with more functionality e.g. commentable & taggableEnhancersEnhance your apps existing functionality e.g. filterWrappersProvide functionality to access 3rd party APIs
  • 4. APIsSource: http://www.programmableweb.com/apis 73% of all APIs (listed on ProgrammableWeb) are RESTful
  • 5. My work so far has been mainly consuming RESTful APIs so this presentation and examples will focus on REST
  • 6. But concepts illustrated in the design approach section later on can be applied to any protocolQuick intro to RESTREspresentational State Transfer“The largest known implementation of a system conforming to the REST architectural style is…” http://en.wikipedia.org/wiki/Representational_State_TransferThe World Wide WebClients and servers communicating via HTTPUses existing HTTP verbs (GET, POST etc)Acts on a resource (URI)
  • 7. HTTPSend request<HTTP verb> <URI> HTTP/1.1<Header 1 name>: <Header 1 value>...<optional body>You’ll get some kind of response (hopefully)HTTP/1.1 <Status Code> <Status Message><Header 1 name>: <Header 1 value>...<optional body>
  • 8. Simple HTTP GET Request & ResponseRequestGET http://www.example.com/index.html HTTP/1.1User-Agent: My Web BrowserResponseHTTP/1.1 200 OKContent-Type: text/htmlContent-Length: 70<html><head><title>My Web Page</title></head><body><h1>My Web Page</h1></body></html>
  • 9. Simple HTTP POST Request & ResponseRequestPOST http://www.example.com/login HTTP/1.1Content-Type: application/x-www-form-urlencodedContent-Length: 38username=neilcrookes&password=abcd1234ResponseHTTP/1.1 301 Moved PermanentlyLocation: http://www.example.com/my_account
  • 10. CakePHP’s HttpSocket Classcake/libs/http_socket.phpUsage: App::import(‘Core’, ‘HttpSocket’); $Http = new HttpSocket(); $response = $Http->request(array( ‘method’ => ‘POST’, ‘uri’ => array( ‘host’ => ‘example.com’, ‘path’ => ‘login’), ‘body’ => array( ‘username’ => ‘neilcrookes’, ‘password’ => ‘abcd1234’)));See HttpSocket::request property for defaults HttpSocketHandles creating, writing to and reading from sockets (because it extends CakeSocket)Constructs HTTP escaped, encoded requests from array parameters you send itParses HTTP response from the server intoStatusBodyCookiesCan handle Basic Auth (username:password@)
  • 11. OAuthIn summary, it allows users of a service (e.g. Twitter) to authorize other parties (i.e. your application) access to their accounts on that service, without sharing their password with the other parties.In reality, it means:a little bit of handshaking between your app and the service provider to get various string tokensredirecting the user to the service in order for them to authorize your app to access their account, so the user only signs in to the service, not your app.the service provides you with a token you can persist and use to make authorized requests to their service on behalf of the userIn practice it’s just an extra header line (Authorization header) in the HTTP request which containssome arbitrary parameters e.g. timestampa token that identifies your application to the API providera signature string that signs the request and is a hash of various request parameters and the secret tokens you retrieved aboveUsed by e.g. Twitter & Google APIs
  • 12. HttpSocketOauthUsage example to tweet “Hello world!”:App::import('Vendor', 'HttpSocketOauth');$Http = new HttpSocketOauth();$response = $Http->request(array( 'method' => 'POST', 'uri' => array( 'host' => 'api.twitter.com', 'path' => '1/statuses/update.json'), 'auth' => array( 'method' => 'OAuth', 'oauth_token' => <oauth token>, 'oauth_token_secret' => <oauth token secret>, 'oauth_consumer_key' => <oauth consumer key>, 'oauth_consumer_secret' => <oauth consumer secret>), 'body' => array( 'status' => 'Hello world!')));http://www.neilcrookes.com/2010/04/12/cakephp-oauth-extension-to-httpsocket/http://github.com/neilcrookes/http_socket_oauth
  • 13. ContentsFoundationsCakePHP plugins, APIs, REST, HTTP, CakePHP HttpSocket, OAuthDesign approachTraditional approach, issues with that, my solutionExamples
  • 14. Traditional approach: DataSourceComplex DataSource containing all the logicCall methods on the DataSource directly from your models or controllersor as implied by the example Twitter DataSource in the cook book: access DataSource methods through your models but include most of the logic in the DataSourcehttp://book.cakephp.org/view/1077/An-ExampleWorks well for simple stuffThis is how I started implementing
  • 15. However...Does not scale well for large APIsTwitter has ~100 API calls available, all with a wide variety of options and parameters. The cook book Twitter DataSource partially implements 2 API calls and is 86 linesDoes not exploit built-in CakePHP goodnessCallbacksValidationPaginationDoes not allow for multiple models (and therefore multiple schemas) to use the same DataSourceDidn’t feel right to me
  • 16. So what does feel right?What operations are we actually doing?Reading dataCreating and updating dataDeleting datai.e. Find, save & deleteWhat type of classes in CakePHP provide these methods?
  • 17. ModelsPhoto by memoflores, available under creative commonshttp://www.flickr.com/photos/memoflores/And what should models be?...
  • 18. FAT!Photo by cstreetus, available under creative commonshttp://www.flickr.com/photos/cstreetus/Sorry but every other image I found through searching for “fat models” or “fat ladies” was completely inappropriate ;-)
  • 19. So if we move our API calls into Model::find(), Model::save() and Model::delete() methodsIt feels like the right placeWe’re more familiar with interacting with theseWe can have lots of simple models classes to achieve scale, separation of concerns and different models can have different validation rules and schemas and we can collect them together in a pluginBut...
  • 20. But what about CakePHP goodness?Triggering callbacksbeforeFind(), afterFind(), beforeSave(), afterSave(), beforeValidate(), beforeDelete(), afterDelete()Triggering validationHandling custom find typesIf we made the API calls directly in these methods and returned the response, to exploit this excellent built-in additional CakePHP functionality we’d have to trigger/code them manuallyWe’d be duplicating loads of code from CakePHP’s core Model class.Not very DRY
  • 21. To understand the solution, we must understand CakePHP Model internalsModel methods like find(), save() and delete() accept various params such as conditions, data to save etcHandle custom find types for find() onlyHandle validation for save() onlyTrigger the before*() callbacksCall create(), read(), update() or delete() on that model’s DataSourceTrigger the after*() callbacksReturn the result
  • 22. So what’s my solution for designing CakePHP plugins for consuming APIs?Plugin containing one model for each type of resource in the API e.g. TwitterStatus or YouTubeVideoModels implement find() (or actually more commonly just CakePHP custom find types), save() and delete() methods as appropriateThese methods set the details of the request, i.e. The array that represents an HTTP request that HttpSocket::request() methods expects (as we saw earlier in this presentation) in a request property of your model, then calls the same method on the parent object i.e. Model.Cont...
  • 23. Solution continuedCakePHP Model class handles validation and custom find types, triggers callbacks etc then calls create(), read(), update() or delete() on the child model’s (your model’s) DataSource, and passes the model objectYour model’s useDbConfig property should be set to a custom DataSource that you also include in your pluginYour DataSource implements the appropriate CRUD method(s) and issues the API call described in the model’s requestproperty, and returns the results
  • 24. Hmmm, sounds complicatedIt’s notI’ve written a REST DataSource you can use (see later)All you have to do is create a model that has find() or save() methods, in which you set a request property to an array expected by HttpSocket::request() and call the same method on the parent.
  • 25. E.g. Creating a tweet<?phpclass TwitterStatus extends AppModel { public function save($data = null) { $this->request = array( 'uri' => array( 'host' => 'api.twitter.com', 'path' => '1/statuses/update.json'), 'body' => array( 'status' => $data['TwitterStatus']['text'])); return parent::save($data); }}?>
  • 26. Which you call like thisClassRegistry::init('Twitter.TwitterStatus')->save(array( 'TwitterStatus' => array( 'text' => “Hello world!”)));... from anywhere you like in your CakePHP application, e.g. In your Post model afterSave() method, thus automatically creating a tweet every time you create a new post.
  • 27. RestSourcehttp://www.neilcrookes.com/2010/06/01/rest-datasource-plugin-for-cakephp/http://github.com/neilcrookes/CakePHP-ReST-DataSource-PluginYou can set your model’s useDbConfigparam to this DataSource, or you can write your own DataSource that extends this oneE.g. Override RestSource::request() to add in the host key in the $model->request property if it’s the same for all API calls, then call parent::(request)
  • 28. This diagram illustrates the flow through the methods an classes involved in creating a tweethttps://docs.google.com/drawings/edit?id=1Aht7huICl9bhl2hWRdM0VdoaBePpJ0kXkceyQpAR8os&hl=en_GB&authkey=CISSqJkN
  • 29. In summaryBy designing plugins like this you’re providingSimple (1 line) method calls to API functionsThat are familiar to all CakePHP bakersAnd easy to documentYou also get to exploit CakePHP goodness such as validation and callbacks etcYou can have multiple models, one for each resource type on the API, each with it’s own schema (which the FormHelper uses) and validation rules
  • 30. ContentsFoundationsCakePHP plugins, APIs, REST, HTTP, CakePHP HttpSocket, OAuthDesign approachTraditional approach, issues with that, my solutionExamples
  • 32. Uploading a YouTube Video – you doClassRegistry::init('Gdata.YouTubeVideo')->save(array( 'YouTubeVideo' => array( 'title' => 'Flying into Chicago Airport', 'description' => 'Filmed through the plane window coming in over the lake', 'category' => 'Travel', 'keywords' => 'Chicago, Plane, Lake, Skyline', 'rate' => 'allowed', 'comment' => 'allowed', 'commentVote' => 'allowed', 'videoRespond' => 'allowed', 'embed' => 'allowed', 'syndicate' => 'allowed', 'private' => 1, 'file' => array( 'name' => 'chicago 1 060.AVI', 'type' => 'video/avi', 'tmp_name' => 'C:indowsemphp6D66.tmp', 'error' => 0, 'size' => 5863102))));
  • 33. Uploading a YouTube Video – plugin createsPOST /feeds/api/users/default/uploads HTTP/1.1Host: uploads.gdata.youtube.comConnection: closeUser-Agent: CakePHPContent-Type: multipart/related; boundary="Next_Part_4c801b22-52e8-4c70-961b-0534fba3b5b1“Slug: chicago 1 060.AVIGdata-Version: 2X-Gdata-Key: key=<my developer key>Authorization: OAuth oauth_version="1.0",oauth_signature_method="HMAC-SHA1",oauth_consumer_key="anonymous",oauth_token=“<my oauth token>",oauth_nonce="fa4b6fc350e19f675f2e5660657e643c",oauth_timestamp="1283463971",oauth_signature="3fIXJ%2BmdV6KLk4zJYszR7M90lIg%3D“Content-Length: 5864289--Next_Part_4c801b22-52e8-4c70-961b-0534fba3b5b1Content-Type: application/atom+xml; charset=UTF-8<?xml version="1.0" encoding="utf-8"?><entry xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" xmlns:yt="http://gdata.youtube.com/schemas/2007"> <media:group> <media:title type="plain">Flying into Chicago Airport</media:title> <media:description type="plain">Filmed through the plane window, shows coming in over the lake</media:description> <media:category scheme="http://gdata.youtube.com/schemas/2007/categories.cat">Travel</media:category> <media:keywords>Chicago, Plane, Lake, Skyline</media:keywords> <yt:private/> </media:group> <yt:accessControl action="rate" permission="allowed"/> <yt:accessControl action="comment" permission="allowed"/> <yt:accessControl action="commentVote" permission="allowed"/>< <yt:accessControl action="videoRespond" permission="allowed"/> <yt:accessControl action="embed" permission="allowed"/> <yt:accessControl action="syndicate" permission="allowed"/></entry> --Next_Part_4c801b22-52e8-4c70-961b-0534fba3b5b1 Content-Type: video/aviContent-Transfer-Encoding: binary<binary file data>