Saturday, March 7, 2015

107 MySuperHero Cloud Registration


.
107 MySuperHero Cloud Registration
In the previous tutorial, we have created a Settings page to store user details in local storage ie SharedPreferences.
In this tutorial, we are going to store the details in the Cloud so that later on the user would be able to perform online Backup and Restore

0) Starting Up

We need a live web site to handle our Cloud service. One of the free options available is www.hostinger.my .
Download the startup files and upload to your hostinger site (or you can also develop it offline first using WAMP package and later upload to hostinger or other hosting provider sites. I preferusbwebserver because it is small).
You need a REST Client Application e.g. Chrome POSTMAN Extension

1) REST Script File

The setup files consist of PHP Scripts and PHP Frameworks (SLIM and NOTORM). Slim is used for easy handling of REST APIs. NOTORM is used for easy interaction with databases.
Check that you have the following folders and files.
The index.php contains PHP Scripts based on SLIM Framework.
<?php
require 'Slim/Slim.php';
require 'NotORM.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
//api-user
$app->post('/users','setUser');
$app->post('/users/:user_id','updateUser');
$app->post('/backup/:user_id','setData');
$app->post('/restore/:user_id','getData');
$app->run();
function setUser() {
        echo "setUser";
}
function updateUser($userid) {
        echo "updateUser for ".$userid;
}
function setData($userid) {
        echo "setData for ".$userid;
}
function getData($userid) {
        echo "getData for ".$userid;
}
?>
Run the REST Client Application (this tutorial uses Chrome Postman Apps) and send the following POST Method Request.

2) Database Setup

We are going to use SQLite database and PDO Class Connection.
The use of PDO Class Connection allows database to be changed later on so that we are not tied to any specific database during development.

2.1) Create Database

Click “Create new database”.
Enter database name “mydb”.

2.2) Create Table

Alternatively, run SQL commands below.
-- Adminer 4.2.4 SQLite 3 dump

DROP TABLE IF EXISTS "tbluserdata";
CREATE TABLE "tbluserdata" (
 "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
 "name" text NULL,
 "email" text NOT NULL,
 "photo" text NULL,
 "superheroes" text NULL
);

--

2.3) Test adding a dummy data.

The above form, when executed, will be translated into the following SQL
INSERT INTO "tbluserdata" ("name", "email", "photo", "superheroes")
VALUES ('boboiboy', 'boboiboy@gmail.com', NULL, NULL);

3) Data Entry Scripts

 3.1) Create database connection script

File: api/data_conn.php
<?php
error_reporting(E_ALL | E_STRICT);
$connection = new PDO("sqlite:../data/mydb.sdb");
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$connection->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER);
//~ $software->debug = true;
?>

3.2) Update API Script File with hardcoded data entries

Test with hardcoded data entries.
File: api/index.php
<?php
require 'Slim/Slim.php';
require 'NotORM.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$app->container->singleton('db', function () {
        include 'data_conn.php';
    return new NotORM($connection);
});
//api-user
$app->post('/users','setUser');
$app->post('/users/:user_id','updateUser');
$app->post('/backup/:user_id','setData');
$app->post('/restore/:user_id','getData');
$app->run();
function setUser() {
        echo "setUser";
        $app = \Slim\Slim::getInstance();
        $db1=$app->db;
        $userdata = $db1->tbluserdata();
        $data = array(
            "name" => "upin",
            "email" => "upin@gmail.com"
        );
        $result = $userdata->insert($data);
}
function updateUser($userid) {
        echo "updateUser for ".$userid;
}
function setData($userid) {
        echo "setData for ".$userid;
}
function getData($userid) {
        echo "getData for ".$userid;
}
?>
OUTCOME.
The SQL result for the above script
INSERT INTO "tbluserdata" ("name", "email", "photo", "superheroes")
VALUES ('upin', 'upin@gmail.com', NULL, NULL);

3.3) Update API Script with Post Parameter Inputs

Test with post parameters.
File: api/index.php
<?php
require 'Slim/Slim.php';
require 'NotORM.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
//$app->$db = new NotORM($connection);
$app->container->singleton('db', function () {
        include 'data_conn.php';
    return new NotORM($connection);
});
//api-user
$app->post('/users','setUser');
$app->post('/users/:user_id','updateUser');
$app->post('/backup/:user_id','setData');
$app->post('/restore/:user_id','getData');
$app->run();
function setUser() {
        //echo "setUser";
        $app = \Slim\Slim::getInstance();
        //create db1 object from app db object
        $db1=$app->db;
        //create userdata object as representation of
        //tbluserdata from db1 connection object
        $userdata = $db1->tbluserdata();
        //create response object as an array
        $response=array();
        $action="none";
        $actionstatus="none";
        $result="0";
        //create variables to store param values
        $name = $app->request->post('name');
        $email = $app->request->post('email');
        //if variables are not empty
        //then assign variable values to data array
        if (!(empty($name)) && !(empty($email)))  {
                //echo 'valid param';
                //find matching useremail to param email
                $registereduser = $db1->tbluserdata("email = ?", $email)->fetch();
                //echo $registereduser;
                //if matched(registered) then update record
                //else insert new record
                if (!empty($registereduser)) {//already registered
                        $action="update";
                    $data = array(
                                "name" => $name
                    );
                    $result = $registereduser->update($data);
                    $actionstatus="success";
                }
                else{
                        $action="insert";
                        $data = array(
                    "name" => $name,
                    "email" => $email
                        );
                        $result = $userdata->insert($data);        
                    $actionstatus="success";                
                }
        }
        //create app response
    $response = $app->response;
    //set response sontent type as json
    $response['Content-Type'] = 'application/json';
    //set response body
    //use json_encode to format the output
    $response->body( json_encode([
        'action' => $action,
        'actionstatus' => $actionstatus,
        'message' => $result
    ]));
}
function updateUser($userid) {
        echo "updateUser for ".$userid;
}
function setData($userid) {
        echo "setData for ".$userid;
}
function getData($userid) {
        echo "getData for ".$userid;
}
?>
OUTCOME.
DATA ENTRY TEST WITH POSTMAN.
DATA ENTRY RESULT TEST WITH ADMINER.
TRY RESUBMITTING IPIN RECORD AGAIN BUT WITH A DIFFERENT NAME.
We have completed a simple exercise to set up REST server using SLIM and NOTORM Framework.
We have created scripts to get post parameter and perform insert or update operation.
In the next tutorial, we will refine the scripts further.
 

DOWNLOAD


.

No comments:

Post a Comment