enterpriseipsum.site

Written in

by

Or how to build a simple webservice with react-php

PHP has network sockets.. so yea, you can build a server with php. But why? Well I’ll tell you why. If your thing is expensive (CPU/Memory) to spin up or needs to respond quickly; having a process waiting for requests is a way to make it way faster than compile,serve,destroy share-nothing that php normally does.

My first test case for this was a talk on PHP-ML library. Yes, machine learning in php. It was pretty fun to play with and a real memory hog. I actually had an excuse to spin up a really big amazon machine with 100GB of memory for a few hours to try out a model I was working on.

Given that took so much memory and time to load, it made sense to use that model like this; attach it to a simple rest service so the model once up could be queried faster. That went well but needed a smaller thing to use as an example. An ipsum generator with Star Trek TNG flair sounded like just the thing. First there was the matter of finding data to feed it. http://chakoteya.net/ hand made transcripts of the TNG episodes. Once molded into a json file of ok size I literally lifted the example code off “reactphp.org”

<?php
require __DIR__ . /config.php
require APPROOT . '/vendor/autoload.php';

//Settings:
$lines = 11904;
$maxLinesOut = 10;

$file = APPROOT . '/data/picard.json';
$quotes = json_decode(file_get_contents($file));

$server = new React\Http\Server(function (Psr\Http\Message\ServerRequestInterface $request) use ($quotes, $lines,$maxLinesOut) {

    $params = $request->getQueryParams();
    $linesOut = 1;
    if(!empty($params['lines'])){
        $linesOut = (int) $params['lines'];
    }
    if($linesOut > $maxLinesOut){
        $linesOut = $maxLinesOut;
    }elseif(empty($linesOut)){
        $linesOut = 1;
    }

    $msg = [];
    $startLine = mt_rand(1,$lines);
    while($linesOut > 0){

        $msg[] = $quotes[$startLine];
        $startLine++;
        $linesOut--;
    }

    return new React\Http\Message\Response(
        200,
        array(
            'Content-Type' => 'application/json',
            'X-Lines'=>count($msg),
        ),
        json_encode($msg),
    );
});

$socket = new React\Socket\Server('0.0.0.0:5000');
$server->listen($socket);
echo "Server running at http://0.0.0.0:5000" . PHP_EOL;

and poof.. one (ugly) web service for getting random quotes which is always in memory and can randomally access the list. I was super happy that I was able to “make it so”.

Go check it out. enterpriseipsum.site

Tags

Categories

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Verified by MonsterInsights