Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Integrating Node.js with PHP

Integrating Node.js with PHP

Presentation I made for PHPHants March 2013 meetup. Also see demo apps:

https://github.com/lboynton/phphants-march-php
https://github.com/lboynton/phphants-march-node

Avatar for Lee Boynton

Lee Boynton

March 23, 2013
Tweet

More Decks by Lee Boynton

Other Decks in Technology

Transcript

  1. Apache + mod_php Webserver Clients (Example borrowed from Marc Gear's

    excellent server side scripting smack down)
  2. A simple Node.js webserver var http = require('http'); http.createServer(function (req,

    res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); }).listen(1337, '127.0.0.1'); console.log('Server running at http://127. 0.0.1:1337/');
  3. • Persistent connection to server via web browser • Low

    latency • Bi-directional • Much better than XHR long polling (comet) Websockets
  4. • 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 Reasons to use PHP still
  5. 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')
  6. Quick example... (PHP) // create connection to memcached $memcached =

    new Memcached(); $memcached->addServer('localhost', 11211); // register handler (PHP 5.3 compatible) $handler = new Lboy\Session\SaveHandler($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';
  7. 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...
  8. Conclusion... • Using Node is fun... • Good way to

    add real-time functionality to existing website • Can be used for much more
  9. 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