Build simple web interface for redis key/value store

Discussion in 'Tutorials and Guides' started by wlanboy, Jan 24, 2016.

  1. wlanboy

    wlanboy Content Contributer

    2,126
    1,169
    May 16, 2013
    This is my second post for php based projects. My first thread is about an IoT plattform for Ardunio clients.


    This post is about creating a simple web interface for a redis key/value store. If you want to install your own redis database you can use this tutorial: 




    I will use following php frameworks to get the rest interface done: Slim, CorSlim, Predis.


    All the server and client code will be available at github: https://github.com/wlanboy/php-redis-rest-service


    a) Server


    We first have to enable CORS support to enable clients of other domains to use our service:


    require ('CorsSlim/CorsSlim.php');
    $app->add(new \CorsSlim\CorsSlim());

    $corsOptions = array(
    "origin" => "*",
    "exposeHeaders" => array("Content-Type", "X-Requested-With", "X-authentication", "X-client"),
    "allowMethods" => array('GET', 'POST', 'PUT', 'DELETE', 'OPTIONS')
    );
    $cors = new \CorsSlim\CorsSlim($corsOptions);
    $app->add($cors);


    After that we have to get a connection to our local redis instance:


    $app->container->singleton('redisclient', function() {
    $client = new Predis\Client('tcp://127.0.0.1:6379');
    return $client;
    });


    And define the routes:


    //Redis routes
    $app->get('/key/:id', 'getKey');
    $app->post('/key', 'addKey');


    And implement them with the help of the Predis framework:


    function getKey($id) {
    $app = \Slim\Slim::getInstance();
    $client = $app->redisclient;
    try {
    $value = $client->get($id);

    $temp = (object) [
    $id => $value
    ];

    echo json_encode($temp);
    } catch(PDOException $e) {
    echo '{"error":{"text":'. $e->getMessage() .'}}';
    }
    }


    Done :)


    b) Client


    I use a simple Ajax JS script for the client. The most simple way to create the GET and POST requests.


    We first defien a data object which is able to create JSON output:


    function KeyValue(key, value) {
    var kv = {"key":key, "value":value};
    kv.toJsonString = function () { return JSON.stringify(kv); };
    return kv;
    };


    And a simple send method that reads form data, sends it to the rest service and prints the response:


    function sendMessage() {
    var key = document.getElementById("postkey").value;
    var value = document.getElementById("postvalue").value;

    if (value == "") {
    jQuery.ajax({
    type: "GET",
    url: "https://rest-api/key/"+key,
    contentType: "application/json; charset=utf-8",
    dataType:"json",
    success: function (data, status, jqXHR) {
    output = document.getElementById("output");
    output.innerHTML = JSON.stringify(data);
    document.getElementById("postkey").focus();
    },

    error: function (jqXHR, status) {
    output = document.getElementById("output");
    output.innerHTML = status;
    document.getElementById("postkey").focus();
    }
    });
    }
    }


    Using GetElementByID + value to get the input.
    Creating a jQuery ajax request and add the key to the url to get the variable stored in redis.


    Same with the POST request to store the value of a variable in redis:


    else{
    var contact = KeyValue(key,value);
    jQuery.ajax({
    type: "POST",
    url: "https://rest-api/key",
    contentType: "application/json; charset=utf-8",
    data: contact.toJsonString(),
    dataType:"json",
    success: function (data, status, jqXHR) {
    output = document.getElementById("output");
    output.innerHTML = JSON.stringify(data);
    document.getElementById("postkey").focus();
    },

    error: function (jqXHR, status) {
    output = document.getElementById("output");
    output.innerHTML = status;
    output.innerHTML += "<br/>";
    output.innerHTML += jqXHR.responseJSON;
    document.getElementById("postkey").focus();
    }
    });

    }


    This time with a data line to get the JSON data of the contact element.


    Same JSON.stringify to get the string representation of the json object.


    Done.


    Simple server & client example to use a redis database without any binary client. Simple HTTP requests to use the redis service.
    I will add additional methods to the rest service to add the other redis commands too.
     
    Last edited by a moderator: Apr 30, 2017
  2. wlanboy

    wlanboy Content Contributer

    2,126
    1,169
    May 16, 2013
    jure likes this.