On the SitePoint PHP blog they've posted a tutorial showing you how to build a chat application with Ratchet, a library in PHP that lets you work with WebSockets for more real-time communication between your frontend and backend systems.
In this tutorial, we’ll be taking a look at Ratchet, a PHP library for working with WebSockets. Let’s start by defining what WebSockets are. MDN says: "WebSockets is an advanced technology that makes it possible to open an interactive communication session between the user’s browser and a server. With this API, you can send messages to a server and receive event-driven responses without having to poll the server for a reply. Connected computers image."WebSockets allow us to write applications that can pass data from the browser to the server and vice-versa in real-time.
They start by helping you get Ratchet installed (via Composer) and start immediate in on the code. They create the application namespace, a Chat
class and client to handle the WebSocket connection. They create methods for the open, close, write and read for the connection and make a simple script with a Ratchet server to handle the messaging back and forth. They also explain the various pieces of the system: the IoServer
, HttpServer
and WsServer
. Finally they help you create the HTML frontend (using jQuery and Handlebars) and the CSS/Javascript to finish off the functionality.