SlideShare ist ein Scribd-Unternehmen logo
1 von 61
Downloaden Sie, um offline zu lesen
Stephan Schmidt | 1&1 Internet AG
JSON-RPC-Proxy Generation with
PHP 5
Connecting PHP and JavaScript
Stephan Schmidt | 1&1 Internet AG
What will I talk about today?
• The Speaker
• Web 2.0 and the Proxy Pattern
• JavaScript-Object-Notation
• JSON in PHP
• The JSON-RPC Specification
• Server- and Clientside JSON-RPC
• Generating Remote Proxies
• SMD and the Dojo Toolkit
Stephan Schmidt | 1&1 Internet AG
Who is Stephan Schmidt?
• Head of Web-Development at 1&1 Internet AG
in Karlsruhe (Java, PHP, JavaScript, XSL)
• Developing PHP since 1999
• Contributor to various Open Source Projects
since 2001 (PEAR, pecl, pat, Stubbles, …)
• Author of „PHP Design Patterns“ and co-author
of several other PHP related books
• Speaker at international conferences since 2001
Stephan Schmidt | 1&1 Internet AG
A classic web application
HTTP/1.x 200 OK
Date: Sat, 24 May 2008 16:28:32 GMT
Server: Apache/2.2.8 (Win32) DAV/2
X-Powered-By: PHP/5.2.5
Content-Length: 299
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html
<html>
<head>
<title>Classic Webapplication</title>
</head>
…
POST /projects/json-rpc/classic/result.php HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://localhost/projects/json-
rpc/classic/form.php
Content-Type: application/x-www-form-urlencoded
Content-Length: 9
a=28&b=14
Stephan Schmidt | 1&1 Internet AG
Classic web applications
• Business logic and presentation layer are
both on the server side
• Every action triggers an HTTP request,
that reloads the complete page
• No functionality in the client
– Except some small JavaScript components
that are not business critical
Stephan Schmidt | 1&1 Internet AG
The business logic layer
class Calculator
{
/**
* Add two numbers
*
* @param int $a
* @param int $b
* @return int
*/
public function add($a, $b)
{
return $a + $b;
}
}
Stephan Schmidt | 1&1 Internet AG
The presentation layer (server-side)
<?php
require_once '../Calculator.php';
$calc = new Calculator();
?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="de"
lang="de">
<head>
<title>Classic Webapplication</title>
</head>
<body>
<h1>Result</h1>
<?php echo $_POST['a']; ?> + <?php echo $_POST['b']; ?> =
<?php echo $calc->add($_POST['a'], $_POST['a']); ?>
</body>
</html>
Stephan Schmidt | 1&1 Internet AG
What has changed with Web 2.0?
Presentation logic has been moved to the
client
– DOM manipulations to show/hide parts of the
page or change content
– Actions do not trigger a reload of the complete
page
BUT: The business logic still resides on the
server and must be accessed by the
presentation layer
Stephan Schmidt | 1&1 Internet AG
How can this dilemma be solved?
• Business logic has to stay in PHP, as you
cannot trust the client
• We need a JavaScript object as a stand-in
for the business logic implemented in PHP
• The presentation layer should make calls
on this object and the calls should
transparently be routed to the business
logic
Stephan Schmidt | 1&1 Internet AG
The Proxy Pattern
Provide a surrogate or placeholder for
another object to control access to it.
Source: http://en.wikipedia.org/wiki/Proxy_pattern
Stephan Schmidt | 1&1 Internet AG
The Remote Proxy Pattern
The Remote Proxy pattern uses a proxy to
hide the fact that a service object is
located on a different machine than the
client objects that want to use it.
Source: http://www.titu.jyu.fi/modpa/Patterns/pattern-RemoteProxy.html
Stephan Schmidt | 1&1 Internet AG
How does this pattern help us?
1. The proxy is implemented in JavaScript
and provides the same public methods
as the business logic class implemented
in PHP
2. The proxy serializes the method call and
sends the request to the server
3. On the server, the request is deserialized
and the requested method is invoked
Stephan Schmidt | 1&1 Internet AG
How does this pattern help us?
4. The return value of the PHP business
logic call again is serialized and sent as
a response
5. On the client, the proxy deserializes the
response and returns the result.
This is completely transparent to the client!
Stephan Schmidt | 1&1 Internet AG
Serializing the method call
Complex data structures need to be
serialized
• anything that could be a parameter of a
method call
• Strings, integers, booleans, arrays,
objects, …
Stephan Schmidt | 1&1 Internet AG
Serializing the method call
Different formats for serializing data are
available
• XML
– XML is very verbose, the requests should be
as small as possible
• PHP‘s serialize format
– Restricted to PHP
• Custom formats (binary or plaintext)
Stephan Schmidt | 1&1 Internet AG
Enter JSON
JSON = JavaScript Object Notation
☺lightweight data-interchange format
☺Easy to read/parse for humans and
machines
☺completely language independent
☺uses conventions that are familiar to
programmers of the C-family of languages
Stephan Schmidt | 1&1 Internet AG
Enter JSON
JSON is built on two structures:
• A collection of name/value pairs. In
various languages, this is realized as an
object, record, struct, dictionary, hash
table, keyed list, or associative array.
• An ordered list of values. In most
languages, this is realized as an array,
vector, list, or sequence.
Stephan Schmidt | 1&1 Internet AG
Objects in JSON
• Set of unordered key/value pairs
• Starts and ends with curly braces
• Key and value are separated by a colon
• Key/value pairs are separated by commas
Stephan Schmidt | 1&1 Internet AG
Arrays in JSON
• Ordered collection of values
• Starts and ends with square brackets
• Values are separated by commas
Stephan Schmidt | 1&1 Internet AG
Values in JSON
• Can be any of the types listed above
• Objects and arrays are also values, which
leads to nesting
Stephan Schmidt | 1&1 Internet AG
JSON examples
Array
(
[0] => 1
[1] => 2
[2] => 3
)
stdClass Object
(
[id] => schst
[mail] => schst@php.net
)
[1,2,3]
{"id":"schst",
"mail":"schst@php.net"}
PHP JSON
Stephan Schmidt | 1&1 Internet AG
JSON in JavaScript
• JSON is a subset of the literal notation of
JavaScript
• Deserialization can be done via eval()
– Leads to security issues
• json.org provides a JSON parser/stringifier
at http://www.json.org/js.html
– Smaller than 2k, if minified
Stephan Schmidt | 1&1 Internet AG
JSON in PHP
• Various parsers / stringifiers are available
– PHP based: Zend_JSON, Solar_JSON, …
– C based: pecl/json
• Since PHP 5.2, the PECL extension is part
of PHP core
– Use it, if possible
• Benchmark available at
http://gggeek.altervista.org/sw/article_20070425.html
Stephan Schmidt | 1&1 Internet AG
Encoding data with PHP
• Extension provides json_encode()
function
• Encodes any value, except resources, in
JSON format
• Requires UTF-8 data
$data = array(1,2,3);
$json = json_encode($data);
Stephan Schmidt | 1&1 Internet AG
Decoding data with PHP
• Extension provides json_decode()
function
• Decodes any JSON-string to PHP data
structures
• Objects can be decoded to stdClass
instances or arrays
$json = "[1,2,3]";
$data = json_decode($json);
Stephan Schmidt | 1&1 Internet AG
Invoking a remote method
Method of an object that is located on a
different machine is invoked via the
network.
Already used in different areas:
• RMI
• SOAP
• XML-RPC
Stephan Schmidt | 1&1 Internet AG
The JSON-RPC protocol
JSON-RPC is a stateless and light-weight
remote procedure call (RPC) protocol for
inter-networking applications over HTTP.
It uses JSON as the data format for all
facets of a remote procedure call,
including all application data carried in
parameters.
Source: http://www.json-rpc.org/
Stephan Schmidt | 1&1 Internet AG
The JSON-RPC protocol
• Inspired by the XML-RPC protocol
• Request and response are serialized in
JSON
• Data is transported via HTTP
• Very often used asynchronously, to avoid
that the application is frozen while the
request is being processed
Stephan Schmidt | 1&1 Internet AG
JSON-RPC Request
The request is a single object with the
following properties:
• method
A string containing the name.
• params
An array of objects
• id
A unique identifier of the request
Stephan Schmidt | 1&1 Internet AG
JSON-RPC Response
The response is a single object with the
following properties:
• result
The result of the method call
• error
An error object, if an error occurred
• id
The same identifier used in the request
Stephan Schmidt | 1&1 Internet AG
JSON-RPC examples
{ "method": "echo",
"params": ["Hello JSON-RPC"],
"id": 1}
{ "result": "Hello JSON-RPC",
"error": null,
"id": 1}
Request
Response
Stephan Schmidt | 1&1 Internet AG
Let’s get practical
• Implement a JavaScript class that
provides a method to call arbitrary JSON-
RPC services
• Implement a PHP script, that acts as a
server for this class
• Use PHP to generate JavaScript proxies
for existing PHP classes that make use of
this JavaScript JSON-RPC client
Stephan Schmidt | 1&1 Internet AG
JSON-RPC Client (simplified)
var JsonRpcClient = function(clientObj) {
// map ids to callbacks
var reqRespMapping = [];
var callback = {
// callback functions for asynchronous calls
}
this.createId = function() {
// create a unique id
};
};
Stephan Schmidt | 1&1 Internet AG
JSON-RPC Client (simplified)
var JsonRpcClient = function(clientObj) {
this.doCall = function(classAndMethod, args) {
var id = this.createId();
var jsonRpcReq = {
method: classAndMethod,
params: arr,
id: id
};
YAHOO.util.Connect.asyncRequest('POST', finalServiceUrl,
callback, jsonRpcReq.toJSONString());
reqRespMapping.push(jsonRpcReq);
return id;
};
};
Stephan Schmidt | 1&1 Internet AG
Using the JSON-RPC Client (simplified)
// Callback object, as calls are asynchronous
var CalculatorCallback = {
callback__add: function(id, result, error) {
alert(result);
}
}
function add() {
var a = document.getElementById('a').value;
var b = document.getElementById('b').value;
var client = new JsonRpcClient(CalculatorCallback);
client.doCall('Calculator.add', [a,b]);
}
Stephan Schmidt | 1&1 Internet AG
JSON-RPC Client
• Name of the PHP class and method has
been separated using a dot (“.”)
• Callback method is called
“callback__$METHOD”
• YUI is used for XmlHttpRequest
abstraction
• The complete code can be downloaded
from http://www.stubbles.net
Stephan Schmidt | 1&1 Internet AG
JSON-RPC Server
• Decode the JSON-RPC request
• Extract the class and the method name
from the “method” property of the request
object
• Dynamically load the class
• Create a stdClass object to contain the
response and copy the id property from
the request
Stephan Schmidt | 1&1 Internet AG
JSON-RPC Server (simplified)
// Get the request
$requestRaw = file_get_contents('php://input');
$request = json_decode($requestRaw);
// Prepare the response
$response = new stdClass();
$response->id = $request->id;
// Get the class and method
$methodRaw = $request->method;
list($class, $method) = explode('.', $methodRaw);
require_once "../{$class}.php";
Stephan Schmidt | 1&1 Internet AG
JSON-RPC Server
• Use the Reflection API to create a new
instance of the class
• Use the Reflection API to dynamically
invoke the method on this instance,
passing the parameters from the JSON-
RPC request
Stephan Schmidt | 1&1 Internet AG
JSON-RPC Server (simplified)
try {
$clazz = new ReflectionClass($class);
$service = $clazz->newInstanceArgs();
// Invoke the method
$methodObj = $clazz->getMethod($method);
$result = $methodObj->invokeArgs($service,
$request->params);
$response->error = null;
$response->result = $result;
} catch (Exception $e) {
}
Stephan Schmidt | 1&1 Internet AG
JSON-RPC Server
• Set the “result” property, if the method
call was successful.
• Catch any exception during processing
and set the “error” property
• Encode the result in JSON and send it to
the browser
Stephan Schmidt | 1&1 Internet AG
JSON-RPC Server (simplified)
try {
…
} catch (Exception $e) {
$response->error = $e->getMessage();
$response->result = null;
}
// Send the response
echo json_encode($response);
Stephan Schmidt | 1&1 Internet AG
A JSON-RPC web application
POST /projects/json-rpc/json-rpc/server.php HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0
Accept-Encoding: gzip,deflate
Keep-Alive: 300
Connection: keep-alive
X-Requested-With: XMLHttpRequest
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://localhost/projects/json-rpc/json-rpc/form.php
Content-Length: 63
Pragma: no-cache
Cache-Control: no-cache
{"method":"Calculator.add","params":["28",
"14"],"id":"1248167"}
HTTP/1.x 200 OK
Date: Sun, 25 May 2008 10:48:44 GMT
Server: Apache/2.2.8 (Win32) DAV/2 mod_ssl/2.2.8 OpenSSL/0.9.8g
mod_autoindex_color PHP/5.2.5
X-Powered-By: PHP/5.2.5
Content-Length: 41
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html
{"id":"1246838","error":null,"result":42}
Stephan Schmidt | 1&1 Internet AG
JSON-RPC Proxy generation
• Dynamically create a JavaScript class,
that encapsulates the doCall() calls on
the JsonRpcClient object
• Use PHP’s reflection API to extract all
public methods from any PHP class
• Provide this functionality over HTTP to
generate the clients on-the-fly.
Stephan Schmidt | 1&1 Internet AG
JSON-RPC Proxy Generator
// dynamically load the class
$className = $_GET['class'];
require_once "../{$className}.php";
$clazz = new ReflectionClass($className);
// Create a JavaScript class for this class
echo "var {$className} = function(clientObj) {n";
echo " this.dispatcher =
new JsonRpcClient(clientObj);n";
echo "};n";
Stephan Schmidt | 1&1 Internet AG
JSON-RPC Proxy Generator
// Iterate over all methods
foreach ($clazz->getMethods() as $method) {
// only export public methods to the proxy
if (!$method->isPublic()) {
continue;
}
$methodName = $method->getName();
// JS generation on next slide
}
Stephan Schmidt | 1&1 Internet AG
JSON-RPC Proxy Generator
// Iterate over all methods
foreach ($clazz->getMethods() as $method) {
$methodName = $method->getName();
echo "{$className}.prototype.{$methodName} =
function() {n";
// route this call to the server
echo “ return this.dispatcher.doCall(
'{$className}.{$methodName}',
arguments);n";
echo "};n";
}
Stephan Schmidt | 1&1 Internet AG
Using the JSON-RPC Proxy generator
• Generated JavaScript code can be loaded
the same way as static JavaScript code,
using the src-attribute of the <script/>
tag
• Generated JavaScript provides a new
JavaScript class that resembles the PHP
class and is used as a proxy
Stephan Schmidt | 1&1 Internet AG
Using the JSON-RPC Proxy generator
<script type="text/javascript"
src="./proxygen.php?class=Calculator"></script>
var Calculator = function(clientObj) {
this.dispatcher = new JsonRpcClient(clientObj);
};
Calculator.prototype.add = function() {
return this.dispatcher.doCall(
'Calculator.add', arguments);
};
Resulting JavaScript
Stephan Schmidt | 1&1 Internet AG
Using the JSON-RPC Proxy
var CalculatorCallback = {
callback__add: function(id, result, error) {
alert(result);
}
}
function add() {
var a = document.getElementById('a').value;
var b = document.getElementById('b').value;
var calc = new Calculator(CalculatorCallback);
calc.add(a, b);
}
Stephan Schmidt | 1&1 Internet AG
Problems with this approach
• Server-side code generates client side
code, which leads to a tight coupling
between PHP code and JavaScript code
• Client framework cannot easily be
replaced
• We need something like WSDL for JSON-
RPC
Stephan Schmidt | 1&1 Internet AG
Enter SMD
SMD = Simple Method Description
• Very easy data structure, that describes all
methods and their parameters, that a
service provides
• Encoded in JSON format
• Invented by the Dojo Toolkit
• Might be replaced by “Service Mapping
Description”
Stephan Schmidt | 1&1 Internet AG
Format of an SMD
SMD always contains:
• The SMD version
• Name of the object or class it represents
• Service type (e.g. JSON-RPC)
• Service URL
• Array of all available methods and their
parameters
Stephan Schmidt | 1&1 Internet AG
Example SMD
{"SMDVersion":".1",
"objectName":"Calculator",
"serviceType":"JSON-RPC",
"serviceURL":"./server.php",
"methods":[
{"name":"add",
"parameters":[
{"name":"a", "type":"INTEGER"},
{"name":"b", "type":"INTEGER"}
]}
]}
Stephan Schmidt | 1&1 Internet AG
Generating SMD with PHP
$className = $_GET['class'];
require_once "../{$className}.php";
$clazz = new ReflectionClass($className);
$smdData = new stdClass();
$smdData->SMDVersion = 1;
$smdData->serviceType = 'JSON-RPC';
$smdData->serviceURL = './server-smd.php?class=' .
$className;
$smdData->objectName = $className;
$smdData->methods = array();
Stephan Schmidt | 1&1 Internet AG
Generating SMD with PHP
foreach ($clazz->getMethods() as $method) {
if (!$method->isPublic()) {
continue;
}
$methodDef = new stdClass();
$methodDef->name = $method->getName();
$methodDef->parameters = array();
$smdData->methods[] = $methodDef;
foreach ($method->getParameters() as $parameter) {
$paramDef = new stdClass();
$paramDef->name = $parameter->getName();
$methodDef->parameters[] = $paramDef;
}
}
echo json_encode($smdData);
Stephan Schmidt | 1&1 Internet AG
Using SMD with the Dojo Toolkit
• First framework that makes use of SMD
• Dynamically generates proxies at run-time
based on an SMD structure, JSON-String
or URL
• Extremely easy to use
• Similar to ext/soap in PHP 5
Stephan Schmidt | 1&1 Internet AG
Using SMD with the Dojo Toolkit
<script type="text/javascript"
src="http://...dojo/dojo.xd.js"></script>
djConfig.usePlainJson = true;
dojo.require('dojo.rpc.JsonService');
var smdURL = './smdgen.php?class=Calculator';
proxy = new dojo.rpc.JsonService(smdURL);
{"SMDVersion":1,"serviceType":"JSON-RPC","serviceURL":"./server-
smd.php?class=Calculator","methods":[{"name":"add","parameters":[{"name":"a"},
{"name":"b"}]}],"objectName":"Calculator"}
Server returns this SMD:
Stephan Schmidt | 1&1 Internet AG
Using the proxy
// Dojo only needs a callback function, no object
function doAddCallback(result) {
alert(result);
}
function add() {
var a = document.getElementById('a').value;
var b = document.getElementById('b').value;
// Execute the call and add the callback
proxy.add(a, b).addCallback(doCalcCallback);
}
Stephan Schmidt | 1&1 Internet AG
Existing Frameworks
Several frameworks already provide the
generation of proxies:
• pecl/SCA_SDO
• PEAR::HTML_AJAX (no real JSON-RPC)
• Sajax (no real JSON-RPC)
• Stubbles
– The only framework that implements the
JSON-RPC and SMD specs
Stephan Schmidt | 1&1 Internet AG
Thank you
Any Questions?
schst@stubbles.net
http://www.stubbles.net
http://www.stubbles.org

Weitere ähnliche Inhalte

Was ist angesagt?

Spring integration with the Java DSL
Spring integration with the Java DSLSpring integration with the Java DSL
Spring integration with the Java DSLBen Wilcock
 
Content Analysis with Apache Tika
Content Analysis with Apache TikaContent Analysis with Apache Tika
Content Analysis with Apache TikaPaolo Mottadelli
 
Overview Of .Net 4.0 Sanjay Vyas
Overview Of .Net 4.0   Sanjay VyasOverview Of .Net 4.0   Sanjay Vyas
Overview Of .Net 4.0 Sanjay Vyasrsnarayanan
 
Text and metadata extraction with Apache Tika
Text and metadata extraction with Apache TikaText and metadata extraction with Apache Tika
Text and metadata extraction with Apache TikaJukka Zitting
 
Attributes, reflection, and dynamic programming
Attributes, reflection, and dynamic programmingAttributes, reflection, and dynamic programming
Attributes, reflection, and dynamic programmingLearnNowOnline
 
5 hs mpostcustomizationrenefonseca
5 hs mpostcustomizationrenefonseca5 hs mpostcustomizationrenefonseca
5 hs mpostcustomizationrenefonsecassuserfadb24
 
Pragmatic REST APIs
Pragmatic REST APIsPragmatic REST APIs
Pragmatic REST APIsamesar0
 
Webinar: Simpler Semantic Search with Solr
Webinar: Simpler Semantic Search with SolrWebinar: Simpler Semantic Search with Solr
Webinar: Simpler Semantic Search with SolrLucidworks
 
TechTalk #13 Grokking: Marrying Elasticsearch with NLP to solve real-world se...
TechTalk #13 Grokking: Marrying Elasticsearch with NLP to solve real-world se...TechTalk #13 Grokking: Marrying Elasticsearch with NLP to solve real-world se...
TechTalk #13 Grokking: Marrying Elasticsearch with NLP to solve real-world se...Grokking VN
 
quickguide-einnovator-11-spring-integration
quickguide-einnovator-11-spring-integrationquickguide-einnovator-11-spring-integration
quickguide-einnovator-11-spring-integrationjorgesimao71
 
Query-time Nonparametric Regression with Temporally Bounded Models - Patrick ...
Query-time Nonparametric Regression with Temporally Bounded Models - Patrick ...Query-time Nonparametric Regression with Temporally Bounded Models - Patrick ...
Query-time Nonparametric Regression with Temporally Bounded Models - Patrick ...Lucidworks
 
Infrastructure crossroads... and the way we walked them in DKPro
Infrastructure crossroads... and the way we walked them in DKProInfrastructure crossroads... and the way we walked them in DKPro
Infrastructure crossroads... and the way we walked them in DKProopenminted_eu
 
Content analysis for ECM with Apache Tika
Content analysis for ECM with Apache TikaContent analysis for ECM with Apache Tika
Content analysis for ECM with Apache TikaPaolo Mottadelli
 
Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programmingChetan Giridhar
 
Webapp security testing
Webapp security testingWebapp security testing
Webapp security testingTomas Doran
 
Rest api design by george reese
Rest api design by george reeseRest api design by george reese
Rest api design by george reesebuildacloud
 
Clean Code III - Software Craftsmanship at SoCal Code Camp San Diego (07/27/2...
Clean Code III - Software Craftsmanship at SoCal Code Camp San Diego (07/27/2...Clean Code III - Software Craftsmanship at SoCal Code Camp San Diego (07/27/2...
Clean Code III - Software Craftsmanship at SoCal Code Camp San Diego (07/27/2...Theo Jungeblut
 

Was ist angesagt? (20)

Spring integration with the Java DSL
Spring integration with the Java DSLSpring integration with the Java DSL
Spring integration with the Java DSL
 
Content Analysis with Apache Tika
Content Analysis with Apache TikaContent Analysis with Apache Tika
Content Analysis with Apache Tika
 
Overview Of .Net 4.0 Sanjay Vyas
Overview Of .Net 4.0   Sanjay VyasOverview Of .Net 4.0   Sanjay Vyas
Overview Of .Net 4.0 Sanjay Vyas
 
Text and metadata extraction with Apache Tika
Text and metadata extraction with Apache TikaText and metadata extraction with Apache Tika
Text and metadata extraction with Apache Tika
 
CBOR - The Better JSON
CBOR - The Better JSONCBOR - The Better JSON
CBOR - The Better JSON
 
Attributes, reflection, and dynamic programming
Attributes, reflection, and dynamic programmingAttributes, reflection, and dynamic programming
Attributes, reflection, and dynamic programming
 
5 hs mpostcustomizationrenefonseca
5 hs mpostcustomizationrenefonseca5 hs mpostcustomizationrenefonseca
5 hs mpostcustomizationrenefonseca
 
Pragmatic REST APIs
Pragmatic REST APIsPragmatic REST APIs
Pragmatic REST APIs
 
Webinar: Simpler Semantic Search with Solr
Webinar: Simpler Semantic Search with SolrWebinar: Simpler Semantic Search with Solr
Webinar: Simpler Semantic Search with Solr
 
TechTalk #13 Grokking: Marrying Elasticsearch with NLP to solve real-world se...
TechTalk #13 Grokking: Marrying Elasticsearch with NLP to solve real-world se...TechTalk #13 Grokking: Marrying Elasticsearch with NLP to solve real-world se...
TechTalk #13 Grokking: Marrying Elasticsearch with NLP to solve real-world se...
 
quickguide-einnovator-11-spring-integration
quickguide-einnovator-11-spring-integrationquickguide-einnovator-11-spring-integration
quickguide-einnovator-11-spring-integration
 
Api and Fluency
Api and FluencyApi and Fluency
Api and Fluency
 
Query-time Nonparametric Regression with Temporally Bounded Models - Patrick ...
Query-time Nonparametric Regression with Temporally Bounded Models - Patrick ...Query-time Nonparametric Regression with Temporally Bounded Models - Patrick ...
Query-time Nonparametric Regression with Temporally Bounded Models - Patrick ...
 
Infrastructure crossroads... and the way we walked them in DKPro
Infrastructure crossroads... and the way we walked them in DKProInfrastructure crossroads... and the way we walked them in DKPro
Infrastructure crossroads... and the way we walked them in DKPro
 
Content analysis for ECM with Apache Tika
Content analysis for ECM with Apache TikaContent analysis for ECM with Apache Tika
Content analysis for ECM with Apache Tika
 
Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programming
 
Apache Tika
Apache TikaApache Tika
Apache Tika
 
Webapp security testing
Webapp security testingWebapp security testing
Webapp security testing
 
Rest api design by george reese
Rest api design by george reeseRest api design by george reese
Rest api design by george reese
 
Clean Code III - Software Craftsmanship at SoCal Code Camp San Diego (07/27/2...
Clean Code III - Software Craftsmanship at SoCal Code Camp San Diego (07/27/2...Clean Code III - Software Craftsmanship at SoCal Code Camp San Diego (07/27/2...
Clean Code III - Software Craftsmanship at SoCal Code Camp San Diego (07/27/2...
 

Andere mochten auch

Mathematical problem solving strategies in plain english
Mathematical problem solving strategies in plain englishMathematical problem solving strategies in plain english
Mathematical problem solving strategies in plain englishAlexander Decker
 
How and why you should spend money on facebook.
How and why you should spend money on facebook.How and why you should spend money on facebook.
How and why you should spend money on facebook.Anyssa Jane
 
eTwinning portal
eTwinning portaleTwinning portal
eTwinning portalnsspt
 
A short tutorial on r
A short tutorial on rA short tutorial on r
A short tutorial on rAshraf Uddin
 

Andere mochten auch (6)

얘너나
얘너나얘너나
얘너나
 
The Malta alternative
The Malta alternativeThe Malta alternative
The Malta alternative
 
Mathematical problem solving strategies in plain english
Mathematical problem solving strategies in plain englishMathematical problem solving strategies in plain english
Mathematical problem solving strategies in plain english
 
How and why you should spend money on facebook.
How and why you should spend money on facebook.How and why you should spend money on facebook.
How and why you should spend money on facebook.
 
eTwinning portal
eTwinning portaleTwinning portal
eTwinning portal
 
A short tutorial on r
A short tutorial on rA short tutorial on r
A short tutorial on r
 

Ähnlich wie Json Rpc Proxy Generation With Php

JSON-RPC Proxy Generation with PHP 5
JSON-RPC Proxy Generation with PHP 5JSON-RPC Proxy Generation with PHP 5
JSON-RPC Proxy Generation with PHP 5Stephan Schmidt
 
Sumo Logic QuickStart Webinar - Jan 2016
Sumo Logic QuickStart Webinar - Jan 2016Sumo Logic QuickStart Webinar - Jan 2016
Sumo Logic QuickStart Webinar - Jan 2016Sumo Logic
 
Basic computers for DIU laptop project students
Basic computers for DIU laptop project studentsBasic computers for DIU laptop project students
Basic computers for DIU laptop project studentsAlauddin Azad
 
Spark Development Lifecycle at Workday - ApacheCon 2020
Spark Development Lifecycle at Workday - ApacheCon 2020Spark Development Lifecycle at Workday - ApacheCon 2020
Spark Development Lifecycle at Workday - ApacheCon 2020Pavel Hardak
 
Apache Spark Development Lifecycle @ Workday - ApacheCon 2020
Apache Spark Development Lifecycle @ Workday - ApacheCon 2020Apache Spark Development Lifecycle @ Workday - ApacheCon 2020
Apache Spark Development Lifecycle @ Workday - ApacheCon 2020Eren Avşaroğulları
 
FDMEE Scripting - Cloud and On-Premises - It Ain't Groovy, But It's My Bread ...
FDMEE Scripting - Cloud and On-Premises - It Ain't Groovy, But It's My Bread ...FDMEE Scripting - Cloud and On-Premises - It Ain't Groovy, But It's My Bread ...
FDMEE Scripting - Cloud and On-Premises - It Ain't Groovy, But It's My Bread ...Joseph Alaimo Jr
 
Synapseindia dot net development web applications with ajax
Synapseindia dot net development  web applications with ajaxSynapseindia dot net development  web applications with ajax
Synapseindia dot net development web applications with ajaxSynapseindiappsdevelopment
 
German introduction to sp framework
German   introduction to sp frameworkGerman   introduction to sp framework
German introduction to sp frameworkBob German
 
Advanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojoAdvanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojoFu Cheng
 
Future-proof Development for Classic SharePoint
Future-proof Development for Classic SharePointFuture-proof Development for Classic SharePoint
Future-proof Development for Classic SharePointBob German
 
Introduction to HTML language Web design.pptx
Introduction to HTML language Web design.pptxIntroduction to HTML language Web design.pptx
Introduction to HTML language Web design.pptxlekhacce
 
Basic of computers
Basic of computers Basic of computers
Basic of computers Harsh Porwal
 
Lares from LOW to PWNED
Lares from LOW to PWNEDLares from LOW to PWNED
Lares from LOW to PWNEDChris Gates
 
PHP Performance: Principles and tools
PHP Performance: Principles and toolsPHP Performance: Principles and tools
PHP Performance: Principles and tools10n Software, LLC
 
05 integrate redis
05 integrate redis05 integrate redis
05 integrate redisErhwen Kuo
 
Structured Functional Automated Web Service Testing
Structured Functional Automated Web Service TestingStructured Functional Automated Web Service Testing
Structured Functional Automated Web Service Testingrdekleijn
 

Ähnlich wie Json Rpc Proxy Generation With Php (20)

JSON-RPC Proxy Generation with PHP 5
JSON-RPC Proxy Generation with PHP 5JSON-RPC Proxy Generation with PHP 5
JSON-RPC Proxy Generation with PHP 5
 
Sanjeev rai
Sanjeev raiSanjeev rai
Sanjeev rai
 
Sumo Logic QuickStart Webinar - Jan 2016
Sumo Logic QuickStart Webinar - Jan 2016Sumo Logic QuickStart Webinar - Jan 2016
Sumo Logic QuickStart Webinar - Jan 2016
 
Basics PHP
Basics PHPBasics PHP
Basics PHP
 
Basic computers for DIU laptop project students
Basic computers for DIU laptop project studentsBasic computers for DIU laptop project students
Basic computers for DIU laptop project students
 
Spark Development Lifecycle at Workday - ApacheCon 2020
Spark Development Lifecycle at Workday - ApacheCon 2020Spark Development Lifecycle at Workday - ApacheCon 2020
Spark Development Lifecycle at Workday - ApacheCon 2020
 
Apache Spark Development Lifecycle @ Workday - ApacheCon 2020
Apache Spark Development Lifecycle @ Workday - ApacheCon 2020Apache Spark Development Lifecycle @ Workday - ApacheCon 2020
Apache Spark Development Lifecycle @ Workday - ApacheCon 2020
 
FDMEE Scripting - Cloud and On-Premises - It Ain't Groovy, But It's My Bread ...
FDMEE Scripting - Cloud and On-Premises - It Ain't Groovy, But It's My Bread ...FDMEE Scripting - Cloud and On-Premises - It Ain't Groovy, But It's My Bread ...
FDMEE Scripting - Cloud and On-Premises - It Ain't Groovy, But It's My Bread ...
 
Synapseindia dot net development web applications with ajax
Synapseindia dot net development  web applications with ajaxSynapseindia dot net development  web applications with ajax
Synapseindia dot net development web applications with ajax
 
German introduction to sp framework
German   introduction to sp frameworkGerman   introduction to sp framework
German introduction to sp framework
 
AD102 - Break out of the Box
AD102 - Break out of the BoxAD102 - Break out of the Box
AD102 - Break out of the Box
 
Advanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojoAdvanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojo
 
Future-proof Development for Classic SharePoint
Future-proof Development for Classic SharePointFuture-proof Development for Classic SharePoint
Future-proof Development for Classic SharePoint
 
025444215.pptx
025444215.pptx025444215.pptx
025444215.pptx
 
Introduction to HTML language Web design.pptx
Introduction to HTML language Web design.pptxIntroduction to HTML language Web design.pptx
Introduction to HTML language Web design.pptx
 
Basic of computers
Basic of computers Basic of computers
Basic of computers
 
Lares from LOW to PWNED
Lares from LOW to PWNEDLares from LOW to PWNED
Lares from LOW to PWNED
 
PHP Performance: Principles and tools
PHP Performance: Principles and toolsPHP Performance: Principles and tools
PHP Performance: Principles and tools
 
05 integrate redis
05 integrate redis05 integrate redis
05 integrate redis
 
Structured Functional Automated Web Service Testing
Structured Functional Automated Web Service TestingStructured Functional Automated Web Service Testing
Structured Functional Automated Web Service Testing
 

Mehr von thinkphp

Knut Morris Pratt Algorithm
Knut Morris Pratt AlgorithmKnut Morris Pratt Algorithm
Knut Morris Pratt Algorithmthinkphp
 
String kmp
String kmpString kmp
String kmpthinkphp
 
String searching
String searching String searching
String searching thinkphp
 
Functional programming in java script
Functional programming in java scriptFunctional programming in java script
Functional programming in java scriptthinkphp
 
Practical functional java script
Practical functional java scriptPractical functional java script
Practical functional java scriptthinkphp
 
Javascript patterns
Javascript patternsJavascript patterns
Javascript patternsthinkphp
 
Placemaker
PlacemakerPlacemaker
Placemakerthinkphp
 
PHP 5.3 And PHP 6 A Look Ahead
PHP 5.3 And PHP 6 A Look AheadPHP 5.3 And PHP 6 A Look Ahead
PHP 5.3 And PHP 6 A Look Aheadthinkphp
 
Atom Web Services
Atom Web ServicesAtom Web Services
Atom Web Servicesthinkphp
 
Php And Web Services
Php And Web ServicesPhp And Web Services
Php And Web Servicesthinkphp
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Conceptsthinkphp
 
Ajax Introduction Presentation
Ajax   Introduction   PresentationAjax   Introduction   Presentation
Ajax Introduction Presentationthinkphp
 
Principii Poo
Principii PooPrincipii Poo
Principii Poothinkphp
 

Mehr von thinkphp (14)

Knut Morris Pratt Algorithm
Knut Morris Pratt AlgorithmKnut Morris Pratt Algorithm
Knut Morris Pratt Algorithm
 
String kmp
String kmpString kmp
String kmp
 
String searching
String searching String searching
String searching
 
Functional programming in java script
Functional programming in java scriptFunctional programming in java script
Functional programming in java script
 
Practical functional java script
Practical functional java scriptPractical functional java script
Practical functional java script
 
Javascript patterns
Javascript patternsJavascript patterns
Javascript patterns
 
Placemaker
PlacemakerPlacemaker
Placemaker
 
PHP 5.3 And PHP 6 A Look Ahead
PHP 5.3 And PHP 6 A Look AheadPHP 5.3 And PHP 6 A Look Ahead
PHP 5.3 And PHP 6 A Look Ahead
 
Atom Web Services
Atom Web ServicesAtom Web Services
Atom Web Services
 
Php And Web Services
Php And Web ServicesPhp And Web Services
Php And Web Services
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
 
Ajax Introduction Presentation
Ajax   Introduction   PresentationAjax   Introduction   Presentation
Ajax Introduction Presentation
 
OOP
OOPOOP
OOP
 
Principii Poo
Principii PooPrincipii Poo
Principii Poo
 

Kürzlich hochgeladen

Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 

Kürzlich hochgeladen (20)

Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 

Json Rpc Proxy Generation With Php

  • 1. Stephan Schmidt | 1&1 Internet AG JSON-RPC-Proxy Generation with PHP 5 Connecting PHP and JavaScript
  • 2. Stephan Schmidt | 1&1 Internet AG What will I talk about today? • The Speaker • Web 2.0 and the Proxy Pattern • JavaScript-Object-Notation • JSON in PHP • The JSON-RPC Specification • Server- and Clientside JSON-RPC • Generating Remote Proxies • SMD and the Dojo Toolkit
  • 3. Stephan Schmidt | 1&1 Internet AG Who is Stephan Schmidt? • Head of Web-Development at 1&1 Internet AG in Karlsruhe (Java, PHP, JavaScript, XSL) • Developing PHP since 1999 • Contributor to various Open Source Projects since 2001 (PEAR, pecl, pat, Stubbles, …) • Author of „PHP Design Patterns“ and co-author of several other PHP related books • Speaker at international conferences since 2001
  • 4. Stephan Schmidt | 1&1 Internet AG A classic web application HTTP/1.x 200 OK Date: Sat, 24 May 2008 16:28:32 GMT Server: Apache/2.2.8 (Win32) DAV/2 X-Powered-By: PHP/5.2.5 Content-Length: 299 Keep-Alive: timeout=5, max=100 Connection: Keep-Alive Content-Type: text/html <html> <head> <title>Classic Webapplication</title> </head> … POST /projects/json-rpc/classic/result.php HTTP/1.1 Host: localhost User-Agent: Mozilla/5.0 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive Referer: http://localhost/projects/json- rpc/classic/form.php Content-Type: application/x-www-form-urlencoded Content-Length: 9 a=28&b=14
  • 5. Stephan Schmidt | 1&1 Internet AG Classic web applications • Business logic and presentation layer are both on the server side • Every action triggers an HTTP request, that reloads the complete page • No functionality in the client – Except some small JavaScript components that are not business critical
  • 6. Stephan Schmidt | 1&1 Internet AG The business logic layer class Calculator { /** * Add two numbers * * @param int $a * @param int $b * @return int */ public function add($a, $b) { return $a + $b; } }
  • 7. Stephan Schmidt | 1&1 Internet AG The presentation layer (server-side) <?php require_once '../Calculator.php'; $calc = new Calculator(); ?> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="de" lang="de"> <head> <title>Classic Webapplication</title> </head> <body> <h1>Result</h1> <?php echo $_POST['a']; ?> + <?php echo $_POST['b']; ?> = <?php echo $calc->add($_POST['a'], $_POST['a']); ?> </body> </html>
  • 8. Stephan Schmidt | 1&1 Internet AG What has changed with Web 2.0? Presentation logic has been moved to the client – DOM manipulations to show/hide parts of the page or change content – Actions do not trigger a reload of the complete page BUT: The business logic still resides on the server and must be accessed by the presentation layer
  • 9. Stephan Schmidt | 1&1 Internet AG How can this dilemma be solved? • Business logic has to stay in PHP, as you cannot trust the client • We need a JavaScript object as a stand-in for the business logic implemented in PHP • The presentation layer should make calls on this object and the calls should transparently be routed to the business logic
  • 10. Stephan Schmidt | 1&1 Internet AG The Proxy Pattern Provide a surrogate or placeholder for another object to control access to it. Source: http://en.wikipedia.org/wiki/Proxy_pattern
  • 11. Stephan Schmidt | 1&1 Internet AG The Remote Proxy Pattern The Remote Proxy pattern uses a proxy to hide the fact that a service object is located on a different machine than the client objects that want to use it. Source: http://www.titu.jyu.fi/modpa/Patterns/pattern-RemoteProxy.html
  • 12. Stephan Schmidt | 1&1 Internet AG How does this pattern help us? 1. The proxy is implemented in JavaScript and provides the same public methods as the business logic class implemented in PHP 2. The proxy serializes the method call and sends the request to the server 3. On the server, the request is deserialized and the requested method is invoked
  • 13. Stephan Schmidt | 1&1 Internet AG How does this pattern help us? 4. The return value of the PHP business logic call again is serialized and sent as a response 5. On the client, the proxy deserializes the response and returns the result. This is completely transparent to the client!
  • 14. Stephan Schmidt | 1&1 Internet AG Serializing the method call Complex data structures need to be serialized • anything that could be a parameter of a method call • Strings, integers, booleans, arrays, objects, …
  • 15. Stephan Schmidt | 1&1 Internet AG Serializing the method call Different formats for serializing data are available • XML – XML is very verbose, the requests should be as small as possible • PHP‘s serialize format – Restricted to PHP • Custom formats (binary or plaintext)
  • 16. Stephan Schmidt | 1&1 Internet AG Enter JSON JSON = JavaScript Object Notation ☺lightweight data-interchange format ☺Easy to read/parse for humans and machines ☺completely language independent ☺uses conventions that are familiar to programmers of the C-family of languages
  • 17. Stephan Schmidt | 1&1 Internet AG Enter JSON JSON is built on two structures: • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array. • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
  • 18. Stephan Schmidt | 1&1 Internet AG Objects in JSON • Set of unordered key/value pairs • Starts and ends with curly braces • Key and value are separated by a colon • Key/value pairs are separated by commas
  • 19. Stephan Schmidt | 1&1 Internet AG Arrays in JSON • Ordered collection of values • Starts and ends with square brackets • Values are separated by commas
  • 20. Stephan Schmidt | 1&1 Internet AG Values in JSON • Can be any of the types listed above • Objects and arrays are also values, which leads to nesting
  • 21. Stephan Schmidt | 1&1 Internet AG JSON examples Array ( [0] => 1 [1] => 2 [2] => 3 ) stdClass Object ( [id] => schst [mail] => schst@php.net ) [1,2,3] {"id":"schst", "mail":"schst@php.net"} PHP JSON
  • 22. Stephan Schmidt | 1&1 Internet AG JSON in JavaScript • JSON is a subset of the literal notation of JavaScript • Deserialization can be done via eval() – Leads to security issues • json.org provides a JSON parser/stringifier at http://www.json.org/js.html – Smaller than 2k, if minified
  • 23. Stephan Schmidt | 1&1 Internet AG JSON in PHP • Various parsers / stringifiers are available – PHP based: Zend_JSON, Solar_JSON, … – C based: pecl/json • Since PHP 5.2, the PECL extension is part of PHP core – Use it, if possible • Benchmark available at http://gggeek.altervista.org/sw/article_20070425.html
  • 24. Stephan Schmidt | 1&1 Internet AG Encoding data with PHP • Extension provides json_encode() function • Encodes any value, except resources, in JSON format • Requires UTF-8 data $data = array(1,2,3); $json = json_encode($data);
  • 25. Stephan Schmidt | 1&1 Internet AG Decoding data with PHP • Extension provides json_decode() function • Decodes any JSON-string to PHP data structures • Objects can be decoded to stdClass instances or arrays $json = "[1,2,3]"; $data = json_decode($json);
  • 26. Stephan Schmidt | 1&1 Internet AG Invoking a remote method Method of an object that is located on a different machine is invoked via the network. Already used in different areas: • RMI • SOAP • XML-RPC
  • 27. Stephan Schmidt | 1&1 Internet AG The JSON-RPC protocol JSON-RPC is a stateless and light-weight remote procedure call (RPC) protocol for inter-networking applications over HTTP. It uses JSON as the data format for all facets of a remote procedure call, including all application data carried in parameters. Source: http://www.json-rpc.org/
  • 28. Stephan Schmidt | 1&1 Internet AG The JSON-RPC protocol • Inspired by the XML-RPC protocol • Request and response are serialized in JSON • Data is transported via HTTP • Very often used asynchronously, to avoid that the application is frozen while the request is being processed
  • 29. Stephan Schmidt | 1&1 Internet AG JSON-RPC Request The request is a single object with the following properties: • method A string containing the name. • params An array of objects • id A unique identifier of the request
  • 30. Stephan Schmidt | 1&1 Internet AG JSON-RPC Response The response is a single object with the following properties: • result The result of the method call • error An error object, if an error occurred • id The same identifier used in the request
  • 31. Stephan Schmidt | 1&1 Internet AG JSON-RPC examples { "method": "echo", "params": ["Hello JSON-RPC"], "id": 1} { "result": "Hello JSON-RPC", "error": null, "id": 1} Request Response
  • 32. Stephan Schmidt | 1&1 Internet AG Let’s get practical • Implement a JavaScript class that provides a method to call arbitrary JSON- RPC services • Implement a PHP script, that acts as a server for this class • Use PHP to generate JavaScript proxies for existing PHP classes that make use of this JavaScript JSON-RPC client
  • 33. Stephan Schmidt | 1&1 Internet AG JSON-RPC Client (simplified) var JsonRpcClient = function(clientObj) { // map ids to callbacks var reqRespMapping = []; var callback = { // callback functions for asynchronous calls } this.createId = function() { // create a unique id }; };
  • 34. Stephan Schmidt | 1&1 Internet AG JSON-RPC Client (simplified) var JsonRpcClient = function(clientObj) { this.doCall = function(classAndMethod, args) { var id = this.createId(); var jsonRpcReq = { method: classAndMethod, params: arr, id: id }; YAHOO.util.Connect.asyncRequest('POST', finalServiceUrl, callback, jsonRpcReq.toJSONString()); reqRespMapping.push(jsonRpcReq); return id; }; };
  • 35. Stephan Schmidt | 1&1 Internet AG Using the JSON-RPC Client (simplified) // Callback object, as calls are asynchronous var CalculatorCallback = { callback__add: function(id, result, error) { alert(result); } } function add() { var a = document.getElementById('a').value; var b = document.getElementById('b').value; var client = new JsonRpcClient(CalculatorCallback); client.doCall('Calculator.add', [a,b]); }
  • 36. Stephan Schmidt | 1&1 Internet AG JSON-RPC Client • Name of the PHP class and method has been separated using a dot (“.”) • Callback method is called “callback__$METHOD” • YUI is used for XmlHttpRequest abstraction • The complete code can be downloaded from http://www.stubbles.net
  • 37. Stephan Schmidt | 1&1 Internet AG JSON-RPC Server • Decode the JSON-RPC request • Extract the class and the method name from the “method” property of the request object • Dynamically load the class • Create a stdClass object to contain the response and copy the id property from the request
  • 38. Stephan Schmidt | 1&1 Internet AG JSON-RPC Server (simplified) // Get the request $requestRaw = file_get_contents('php://input'); $request = json_decode($requestRaw); // Prepare the response $response = new stdClass(); $response->id = $request->id; // Get the class and method $methodRaw = $request->method; list($class, $method) = explode('.', $methodRaw); require_once "../{$class}.php";
  • 39. Stephan Schmidt | 1&1 Internet AG JSON-RPC Server • Use the Reflection API to create a new instance of the class • Use the Reflection API to dynamically invoke the method on this instance, passing the parameters from the JSON- RPC request
  • 40. Stephan Schmidt | 1&1 Internet AG JSON-RPC Server (simplified) try { $clazz = new ReflectionClass($class); $service = $clazz->newInstanceArgs(); // Invoke the method $methodObj = $clazz->getMethod($method); $result = $methodObj->invokeArgs($service, $request->params); $response->error = null; $response->result = $result; } catch (Exception $e) { }
  • 41. Stephan Schmidt | 1&1 Internet AG JSON-RPC Server • Set the “result” property, if the method call was successful. • Catch any exception during processing and set the “error” property • Encode the result in JSON and send it to the browser
  • 42. Stephan Schmidt | 1&1 Internet AG JSON-RPC Server (simplified) try { … } catch (Exception $e) { $response->error = $e->getMessage(); $response->result = null; } // Send the response echo json_encode($response);
  • 43. Stephan Schmidt | 1&1 Internet AG A JSON-RPC web application POST /projects/json-rpc/json-rpc/server.php HTTP/1.1 Host: localhost User-Agent: Mozilla/5.0 Accept-Encoding: gzip,deflate Keep-Alive: 300 Connection: keep-alive X-Requested-With: XMLHttpRequest Content-Type: application/x-www-form-urlencoded; charset=UTF-8 Referer: http://localhost/projects/json-rpc/json-rpc/form.php Content-Length: 63 Pragma: no-cache Cache-Control: no-cache {"method":"Calculator.add","params":["28", "14"],"id":"1248167"} HTTP/1.x 200 OK Date: Sun, 25 May 2008 10:48:44 GMT Server: Apache/2.2.8 (Win32) DAV/2 mod_ssl/2.2.8 OpenSSL/0.9.8g mod_autoindex_color PHP/5.2.5 X-Powered-By: PHP/5.2.5 Content-Length: 41 Keep-Alive: timeout=5, max=100 Connection: Keep-Alive Content-Type: text/html {"id":"1246838","error":null,"result":42}
  • 44. Stephan Schmidt | 1&1 Internet AG JSON-RPC Proxy generation • Dynamically create a JavaScript class, that encapsulates the doCall() calls on the JsonRpcClient object • Use PHP’s reflection API to extract all public methods from any PHP class • Provide this functionality over HTTP to generate the clients on-the-fly.
  • 45. Stephan Schmidt | 1&1 Internet AG JSON-RPC Proxy Generator // dynamically load the class $className = $_GET['class']; require_once "../{$className}.php"; $clazz = new ReflectionClass($className); // Create a JavaScript class for this class echo "var {$className} = function(clientObj) {n"; echo " this.dispatcher = new JsonRpcClient(clientObj);n"; echo "};n";
  • 46. Stephan Schmidt | 1&1 Internet AG JSON-RPC Proxy Generator // Iterate over all methods foreach ($clazz->getMethods() as $method) { // only export public methods to the proxy if (!$method->isPublic()) { continue; } $methodName = $method->getName(); // JS generation on next slide }
  • 47. Stephan Schmidt | 1&1 Internet AG JSON-RPC Proxy Generator // Iterate over all methods foreach ($clazz->getMethods() as $method) { $methodName = $method->getName(); echo "{$className}.prototype.{$methodName} = function() {n"; // route this call to the server echo “ return this.dispatcher.doCall( '{$className}.{$methodName}', arguments);n"; echo "};n"; }
  • 48. Stephan Schmidt | 1&1 Internet AG Using the JSON-RPC Proxy generator • Generated JavaScript code can be loaded the same way as static JavaScript code, using the src-attribute of the <script/> tag • Generated JavaScript provides a new JavaScript class that resembles the PHP class and is used as a proxy
  • 49. Stephan Schmidt | 1&1 Internet AG Using the JSON-RPC Proxy generator <script type="text/javascript" src="./proxygen.php?class=Calculator"></script> var Calculator = function(clientObj) { this.dispatcher = new JsonRpcClient(clientObj); }; Calculator.prototype.add = function() { return this.dispatcher.doCall( 'Calculator.add', arguments); }; Resulting JavaScript
  • 50. Stephan Schmidt | 1&1 Internet AG Using the JSON-RPC Proxy var CalculatorCallback = { callback__add: function(id, result, error) { alert(result); } } function add() { var a = document.getElementById('a').value; var b = document.getElementById('b').value; var calc = new Calculator(CalculatorCallback); calc.add(a, b); }
  • 51. Stephan Schmidt | 1&1 Internet AG Problems with this approach • Server-side code generates client side code, which leads to a tight coupling between PHP code and JavaScript code • Client framework cannot easily be replaced • We need something like WSDL for JSON- RPC
  • 52. Stephan Schmidt | 1&1 Internet AG Enter SMD SMD = Simple Method Description • Very easy data structure, that describes all methods and their parameters, that a service provides • Encoded in JSON format • Invented by the Dojo Toolkit • Might be replaced by “Service Mapping Description”
  • 53. Stephan Schmidt | 1&1 Internet AG Format of an SMD SMD always contains: • The SMD version • Name of the object or class it represents • Service type (e.g. JSON-RPC) • Service URL • Array of all available methods and their parameters
  • 54. Stephan Schmidt | 1&1 Internet AG Example SMD {"SMDVersion":".1", "objectName":"Calculator", "serviceType":"JSON-RPC", "serviceURL":"./server.php", "methods":[ {"name":"add", "parameters":[ {"name":"a", "type":"INTEGER"}, {"name":"b", "type":"INTEGER"} ]} ]}
  • 55. Stephan Schmidt | 1&1 Internet AG Generating SMD with PHP $className = $_GET['class']; require_once "../{$className}.php"; $clazz = new ReflectionClass($className); $smdData = new stdClass(); $smdData->SMDVersion = 1; $smdData->serviceType = 'JSON-RPC'; $smdData->serviceURL = './server-smd.php?class=' . $className; $smdData->objectName = $className; $smdData->methods = array();
  • 56. Stephan Schmidt | 1&1 Internet AG Generating SMD with PHP foreach ($clazz->getMethods() as $method) { if (!$method->isPublic()) { continue; } $methodDef = new stdClass(); $methodDef->name = $method->getName(); $methodDef->parameters = array(); $smdData->methods[] = $methodDef; foreach ($method->getParameters() as $parameter) { $paramDef = new stdClass(); $paramDef->name = $parameter->getName(); $methodDef->parameters[] = $paramDef; } } echo json_encode($smdData);
  • 57. Stephan Schmidt | 1&1 Internet AG Using SMD with the Dojo Toolkit • First framework that makes use of SMD • Dynamically generates proxies at run-time based on an SMD structure, JSON-String or URL • Extremely easy to use • Similar to ext/soap in PHP 5
  • 58. Stephan Schmidt | 1&1 Internet AG Using SMD with the Dojo Toolkit <script type="text/javascript" src="http://...dojo/dojo.xd.js"></script> djConfig.usePlainJson = true; dojo.require('dojo.rpc.JsonService'); var smdURL = './smdgen.php?class=Calculator'; proxy = new dojo.rpc.JsonService(smdURL); {"SMDVersion":1,"serviceType":"JSON-RPC","serviceURL":"./server- smd.php?class=Calculator","methods":[{"name":"add","parameters":[{"name":"a"}, {"name":"b"}]}],"objectName":"Calculator"} Server returns this SMD:
  • 59. Stephan Schmidt | 1&1 Internet AG Using the proxy // Dojo only needs a callback function, no object function doAddCallback(result) { alert(result); } function add() { var a = document.getElementById('a').value; var b = document.getElementById('b').value; // Execute the call and add the callback proxy.add(a, b).addCallback(doCalcCallback); }
  • 60. Stephan Schmidt | 1&1 Internet AG Existing Frameworks Several frameworks already provide the generation of proxies: • pecl/SCA_SDO • PEAR::HTML_AJAX (no real JSON-RPC) • Sajax (no real JSON-RPC) • Stubbles – The only framework that implements the JSON-RPC and SMD specs
  • 61. Stephan Schmidt | 1&1 Internet AG Thank you Any Questions? schst@stubbles.net http://www.stubbles.net http://www.stubbles.org