SlideShare una empresa de Scribd logo
1 de 24
Descargar para leer sin conexión
Integrating Node.js with
          PHP
         Lee Boynton
  PHPHants March 2013 Meetup
So... WTF is Node.js?
Server-side JavaScript
It's single threaded...
...one process serves
    multiple clients
Apache + mod_php
         Clients                                                     Webserver




    (Example borrowed from Marc Gear's excellent server side scripting smack down)
nginx + php-fpm
Still pretty similar, there is a pool of available
                 PHP processes
Node.js
      Clients   Webserver
A simple Node.js webserver
var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type':
'text/plain'});
  res.end('Hello Worldn');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.
0.0.1:1337/');
Why should I use Node.js
        then?
#1 Reason
  l33tness
Use same language on
  the frontend and
      backend!
Websockets!!!!
Websockets
● Persistent connection to server via web
  browser
● Low latency
● Bi-directional
● Much better than XHR long polling (comet)
The possibilities...
●   Games
●   News feeds
●   Chat
●   Real-time applications
Awesome!
     Let's ditch PHP!
Or use the right tool for the right job...
Reasons to use PHP still
●   PHP works
●   Familiarity, maturity
●   Existing code in PHP
●   Node still in its infancy (created in 2009)
    ○ Not as many frameworks, libraries
    ○ May have to write more code for some basic things
    ○ APIs may change, not version 1.0 yet
Oh yeah, the integrating part...


                     Memcache/redis/
                      something else


      Session data                     Session data




        PHP                                  Node
However...
Sessions are serialized by PHP:
not|a:2:{i:0;s:4:"easy";i:1;a:1:{s:2:"to";s:5:"parse";}}


Easier to parse JSON in Node.js:
{"this": {"is": "easier"}}
Use my session save handler...
On Packagist: lboynton/memcached-json-
session-save-handler

Or msgpack: https://github.
com/msgpack/msgpack-php
● ini_set('session.serialize_handler', 'msgpack')
Quick example... (PHP)
  // create connection to memcached
  $memcached = new Memcached();
  $memcached->addServer('localhost', 11211);

  // register handler (PHP 5.3 compatible)
  $handler = new LboySessionSaveHandler($memcached);

  session_set_save_handler(
     array($handler, 'open'),
     array($handler, 'close'),
     array($handler, 'read'),
     array($handler, 'write'),
     array($handler, 'destroy'),
     array($handler, 'gc')
  );

  register_shutdown_function('session_write_close');
  session_start();

  // start using the session
  $_SESSION['serialisation'] = 'this should be in json';
Quick example... (Node.js)
1. Get session ID from cookie
2. Get session data out of memcached
3. Use session data to identify client and send
   relevant info to their browser

See demo app...
Conclusion...
● Using Node is fun...
● Good way to add real-time functionality to
  existing website
● Can be used for much more
Links
● http://nodejs.org/
● https://npmjs.org/
● http://socket.io/
● https://packagist.
  org/packages/lboynton/memcached-json-
  session-save-handler
● https://github.com/msgpack/msgpack-php
● https://github.com/msgpack/msgpack-node

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Nodeconf npm 2011
Nodeconf npm 2011Nodeconf npm 2011
Nodeconf npm 2011
 
Understanding Non Blocking I/O with Python
Understanding Non Blocking I/O with PythonUnderstanding Non Blocking I/O with Python
Understanding Non Blocking I/O with Python
 
Cache hcm-topdev
Cache hcm-topdevCache hcm-topdev
Cache hcm-topdev
 
The MEAN Stack: MongoDB, ExpressJS, AngularJS and Node.js
The MEAN Stack: MongoDB, ExpressJS, AngularJS and Node.jsThe MEAN Stack: MongoDB, ExpressJS, AngularJS and Node.js
The MEAN Stack: MongoDB, ExpressJS, AngularJS and Node.js
 
Sơ lược kiến trúc hệ thống Zing Me
Sơ lược kiến trúc hệ thống Zing MeSơ lược kiến trúc hệ thống Zing Me
Sơ lược kiến trúc hệ thống Zing Me
 
JavaScript development methodology
JavaScript development methodologyJavaScript development methodology
JavaScript development methodology
 
Node js (runtime environment + js library) platform
Node js (runtime environment + js library) platformNode js (runtime environment + js library) platform
Node js (runtime environment + js library) platform
 
Chromium: NaCl and Pepper API
Chromium: NaCl and Pepper APIChromium: NaCl and Pepper API
Chromium: NaCl and Pepper API
 
Create Rest API in Nodejs
Create Rest API in Nodejs Create Rest API in Nodejs
Create Rest API in Nodejs
 
ServiceWorker: New game changer is coming!
ServiceWorker: New game changer is coming!ServiceWorker: New game changer is coming!
ServiceWorker: New game changer is coming!
 
PHP Application Performance
PHP Application PerformancePHP Application Performance
PHP Application Performance
 
Node js first look - 2016
Node js first look - 2016Node js first look - 2016
Node js first look - 2016
 
Fast Slim Correct: The History and Evolution of JavaScript.
Fast Slim Correct: The History and Evolution of JavaScript.Fast Slim Correct: The History and Evolution of JavaScript.
Fast Slim Correct: The History and Evolution of JavaScript.
 
Server-side JavaScript for the rest of us
Server-side JavaScript for the rest of usServer-side JavaScript for the rest of us
Server-side JavaScript for the rest of us
 
Production Ready Javascript With Grunt
Production Ready Javascript With GruntProduction Ready Javascript With Grunt
Production Ready Javascript With Grunt
 
Headless approach and Acquia - Case study - Chris Ozog
Headless approach and Acquia - Case study - Chris OzogHeadless approach and Acquia - Case study - Chris Ozog
Headless approach and Acquia - Case study - Chris Ozog
 
Java script
Java scriptJava script
Java script
 
DevDay 2018 - Blazor
DevDay 2018 - BlazorDevDay 2018 - Blazor
DevDay 2018 - Blazor
 
More efficient, usable web
More efficient, usable webMore efficient, usable web
More efficient, usable web
 
Front-end development automation with Grunt
Front-end development automation with GruntFront-end development automation with Grunt
Front-end development automation with Grunt
 

Similar a Integrating Node.js with PHP

Node js
Node jsNode js
Node js
hazzaz
 
Matt Gauger - Lamp vs. the world - MKE PHP Users Group - December 14, 2010
Matt Gauger - Lamp vs. the world - MKE PHP Users Group - December 14, 2010 Matt Gauger - Lamp vs. the world - MKE PHP Users Group - December 14, 2010
Matt Gauger - Lamp vs. the world - MKE PHP Users Group - December 14, 2010
Matt Gauger
 
Node.js for Rubists
Node.js for RubistsNode.js for Rubists
Node.js for Rubists
Sagiv Ofek
 

Similar a Integrating Node.js with PHP (20)

Server Side Event Driven Programming
Server Side Event Driven ProgrammingServer Side Event Driven Programming
Server Side Event Driven Programming
 
Event driven programming -- Node.JS
Event driven programming -- Node.JSEvent driven programming -- Node.JS
Event driven programming -- Node.JS
 
NodeJS
NodeJSNodeJS
NodeJS
 
Nginx pres
Nginx presNginx pres
Nginx pres
 
Nodejs
NodejsNodejs
Nodejs
 
(phpconftw2012) PHP as a Middleware in Embedded Systems
(phpconftw2012) PHP as a Middleware in Embedded Systems(phpconftw2012) PHP as a Middleware in Embedded Systems
(phpconftw2012) PHP as a Middleware in Embedded Systems
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backend
 
GeekCampSG - Nodejs , Websockets and Realtime Web
GeekCampSG - Nodejs , Websockets and Realtime WebGeekCampSG - Nodejs , Websockets and Realtime Web
GeekCampSG - Nodejs , Websockets and Realtime Web
 
Difference between php and node
Difference between php and nodeDifference between php and node
Difference between php and node
 
Node.js
Node.jsNode.js
Node.js
 
HTTP, JSON, JavaScript, Map&Reduce built-in to MySQL
HTTP, JSON, JavaScript, Map&Reduce built-in to MySQLHTTP, JSON, JavaScript, Map&Reduce built-in to MySQL
HTTP, JSON, JavaScript, Map&Reduce built-in to MySQL
 
Developing realtime apps with Drupal and NodeJS
Developing realtime apps with Drupal and NodeJS Developing realtime apps with Drupal and NodeJS
Developing realtime apps with Drupal and NodeJS
 
Node js
Node jsNode js
Node js
 
Matt Gauger - Lamp vs. the world - MKE PHP Users Group - December 14, 2010
Matt Gauger - Lamp vs. the world - MKE PHP Users Group - December 14, 2010 Matt Gauger - Lamp vs. the world - MKE PHP Users Group - December 14, 2010
Matt Gauger - Lamp vs. the world - MKE PHP Users Group - December 14, 2010
 
Node.js - The New, New Hotness
Node.js - The New, New HotnessNode.js - The New, New Hotness
Node.js - The New, New Hotness
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Node.js for Rubists
Node.js for RubistsNode.js for Rubists
Node.js for Rubists
 
PHP vs Node.js
PHP vs Node.jsPHP vs Node.js
PHP vs Node.js
 
node.js - Fast event based web application development
node.js - Fast event based web application developmentnode.js - Fast event based web application development
node.js - Fast event based web application development
 
Introduction to node.js
Introduction to  node.jsIntroduction to  node.js
Introduction to node.js
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Último (20)

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 

Integrating Node.js with PHP

  • 1. Integrating Node.js with PHP Lee Boynton PHPHants March 2013 Meetup
  • 2. So... WTF is Node.js?
  • 5. ...one process serves multiple clients
  • 6. Apache + mod_php Clients Webserver (Example borrowed from Marc Gear's excellent server side scripting smack down)
  • 7. nginx + php-fpm Still pretty similar, there is a pool of available PHP processes
  • 8. Node.js Clients Webserver
  • 9. A simple Node.js webserver var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello Worldn'); }).listen(1337, '127.0.0.1'); console.log('Server running at http://127. 0.0.1:1337/');
  • 10. Why should I use Node.js then?
  • 11. #1 Reason l33tness
  • 12. Use same language on the frontend and backend!
  • 14. Websockets ● Persistent connection to server via web browser ● Low latency ● Bi-directional ● Much better than XHR long polling (comet)
  • 15. The possibilities... ● Games ● News feeds ● Chat ● Real-time applications
  • 16. Awesome! Let's ditch PHP! Or use the right tool for the right job...
  • 17. Reasons to use PHP still ● PHP works ● Familiarity, maturity ● Existing code in PHP ● Node still in its infancy (created in 2009) ○ Not as many frameworks, libraries ○ May have to write more code for some basic things ○ APIs may change, not version 1.0 yet
  • 18. Oh yeah, the integrating part... Memcache/redis/ something else Session data Session data PHP Node
  • 19. However... Sessions are serialized by PHP: not|a:2:{i:0;s:4:"easy";i:1;a:1:{s:2:"to";s:5:"parse";}} Easier to parse JSON in Node.js: {"this": {"is": "easier"}}
  • 20. Use my session save handler... On Packagist: lboynton/memcached-json- session-save-handler Or msgpack: https://github. com/msgpack/msgpack-php ● ini_set('session.serialize_handler', 'msgpack')
  • 21. Quick example... (PHP) // create connection to memcached $memcached = new Memcached(); $memcached->addServer('localhost', 11211); // register handler (PHP 5.3 compatible) $handler = new LboySessionSaveHandler($memcached); session_set_save_handler( array($handler, 'open'), array($handler, 'close'), array($handler, 'read'), array($handler, 'write'), array($handler, 'destroy'), array($handler, 'gc') ); register_shutdown_function('session_write_close'); session_start(); // start using the session $_SESSION['serialisation'] = 'this should be in json';
  • 22. Quick example... (Node.js) 1. Get session ID from cookie 2. Get session data out of memcached 3. Use session data to identify client and send relevant info to their browser See demo app...
  • 23. Conclusion... ● Using Node is fun... ● Good way to add real-time functionality to existing website ● Can be used for much more
  • 24. Links ● http://nodejs.org/ ● https://npmjs.org/ ● http://socket.io/ ● https://packagist. org/packages/lboynton/memcached-json- session-save-handler ● https://github.com/msgpack/msgpack-php ● https://github.com/msgpack/msgpack-node