Wednesday, February 24, 2016

Websockets in Your Synchronous Site

I’m always yammering on about writing asynchronous PHP code, and for a reason. I think it’s healthy to get fresh perspectives - to be exposed to new programming paradigms.

Asynchronous architecture is common in other programming languages, but it’s only just finding its feet in PHP. The trouble is that this new architecture comes with a cost.

I don’t talk about that cost enough.

When I recommend frameworks like Icicle, ReactPHP, and AMPHP, the obvious place to start with them is to create something new. If you have an existing site (perhaps running through Apache or Nginx), adding daemonised PHP services to your app is probably not as easy as just starting over.

Abstract image of data streaming in parallel

It takes a lot of work to integrate new, asynchronous features into existing applications. Often there are good reasons and great benefits, but a rewrite is always a hard-sell. Perhaps you can get some of the benefits of parallel execution without using an event loop. Perhaps you can get some of the benefits of web sockets without a new architecture.

I’m going to show you a Sockets-as-a-Service service, called Socketize. Try saying that a few times, out loud…

Note: Web sockets involve a fair amount of JavaScript. Fortunately, we don’t need to set up any complicated build chains. You can find the example code for this tutorial here.

Setup!

Let’s set up a simple CRUD example. Download the SQL script, and import it to a local database. Then let’s create a JSON endpoint:

$action = "/get";
$actions = ["/get"];

if (isset($_SERVER["PATH_INFO"])) {
    if (in_array($_SERVER["PATH_INFO"], $actions)) {
        $action = $_SERVER["PATH_INFO"];
    }
}

$db = new PDO(
    "mysql:host=localhost;dbname=[your_database_name];charset=utf8",
    "[your_database_username]",
    "[your_database_password]"
);

function respond($data) {
    header("Content-type: application/json");
    print json_encode($data) and exit;
}

This code will decide whether a request is being made against a valid endpoint (currently only supporting /get). We also establish a connection to the database, and define a method for allowing us to respond to the browser with minimal effort.

Continue reading %Websockets in Your Synchronous Site%


by Christopher Pitt via SitePoint

No comments:

Post a Comment