Callbacks & Promise in node js

Today i will share the Node JS callback and promise system. Node JS asynchronous event based language which mean system not wait for task for completion and forward to next instruction. So as an example if we try to read a file from file system and then print read contents that may not work.

const fs = require ("fs");
let content = fs.reafile ("file.txt"):
console.log (content):

In above code, interpretor jump to console log even before read file call completion due to asynchronous behavior.
This issue is resolved by Node JS by making all its core APIs async friendly through callbacks. Above example actually work like below.

const fs = require ("fs");
let content = fs.reafile ("file.txt", function (err, data){
     if (err ){
          console.log (err);
     }
     console.log (data):
}):

Here readfile api provide a callback function which executed after file read operation. It have two arguments err and data. Data have the success response, in case of readfile api, file contents.
Node JS core APIs work like that. Provide a callback function with error and response as parameters. We can implement our callbacks similar to this for asynchronous tasks.

funtion asyncfunction (inp, callback ){
     // do some asyns task
     const http = require ("http");
     http.get (url, function (err, response){
         callback (response);
     });
}

Above function can be used like

asyncfunction( data, function (httpResponse) {
      console.log( httpResponse);
});

In this case we can get interesting pattern like below.

 func1(data, function() {
    data.mod1 = 1;
    func2(data, function() {
        data.mod2 = 2;
        func3(data, function() {
            data.mod3 = 3;
            func4(data, function() {
                 data.mod4 = 4;
                 console.log( data);
            })
        });
    });
});

Above code show hierarchy of callbacks, Also famously called Callback Hell. This is problematic due to Poor readability & Poor manageability. Their are multiple solutions for ignore callback hells.
First to use modular code like I previously done in asyncfunction.

Second approach is to use Promises. Promise give us better control of asynchronous code.
Promise have two results states. Resolve & Reject. In Core Node JS we can use promise like that

function MyPromisedFunc() {
    return new Promise( resolve, reject ) {
         http.get(url, function(err, response) {
             if( err ) {
                  reject(‘Error in http response’)
             }
             resolve(response);
        });
   });
 }

return MyPromisedFunc() .then(function(response) {
     console.log(response);
 }).catch(function(err) {
     console.log(err); 
 });

Above code is more readable and manageable then callback code. Any time of our async code when we get actual response, we only need to resolve promise, If we get error the we reject the promise.
This further handle by then & catch blocks.
This is more look clear in multiple async function which need to run synchronously.

return MyPromisedFunc1()
     .then(MyPromisedFunc2)
     .then(MyPromisedFunc3)
     .then(MyPromisedFunc4) 
     .then(function(response) {
          console.log(response);
     }).catch(function(err) {
          console.log(err); 
     });

Now we executed four asynchronous functionalities in sync manner with better manageability.
Promise core api functionality is still very much limited in terms of functionality compare to third party Promise libraries like bluebird, Q Promise and more.

Example in bluebird support execution in parallel with better control.

const bluebirdPromise = require(‘bluebird’);
return bluebirdPromise.all([
     MyPromisedFunc1(),
     MyPromisedFunc2(),
     MyPromisedFunc3(),
     MyPromisedFunc4() ],
     .then(function(responseArray) {
           console.log(responseArray[0]);
           console.log(responseArray[1]);
           console.log(responseArray[2]);
           console.log(responseArray[3]); 
     }).catch(function(err) {
          console.log(err); 
     });

Node REST API Testing with Jasmine

In last article REST using Node/Express & Mongoose , I talk about setting REST APIs in NodeJS, Express & Mongoose. Today I will discuss unit testing for REST APIs using Jasmine.

Jasmine is behavioral testing framework for javascript applications. It provide easy to write & understand testing rules. While it can be downloaded from https://github.com/jasmine/jasmine. In node js we would use npm package named jasmine-node.

$ npm install --save jasmine-node

We also install request package for easy http calls.

$ npm install --save request

Now create a test folder let we name it spec. We can define our test cases in this folder. Let create a file names hello.spec.js and Put following code into it

describe("Hello World Suite", function() {
    it("check if text is 'Hello World'", function(done) {
        let text = "Hello World";
        expect(text).toBe("Hello World");
        done();
    });
   it("check if another text is 'Hello World'", function(done) {
        let text = "Not Hello World";
        expect(text).toBe("Hello World");
        done();
    });
});

Now we run command

$ node_modules/.bin/jasmine-node spec

This command generate assert failures for second test like below

Failures:

1) Hello World Suite check if another text is 'Hello World'
 Message:
 Expected 'Not Hello World' to be 'Hello World'.

2 tests, 2 assertions, 1 failure, 0 skipped

If we change text in second test from “Not Hello World” to “Hello World”  and re run command. We will get assert success like below .

2 tests, 2 assertions, 0 failures, 0 skipped

In above test “describe” work as Test Suite, So it can have many related tests, Let example for particular form field data validations, So all validation like not-empty, data type, duplicate can be part of single suite. describe have definition which show use of suite

individual tests inside described via “it”, which have suite description as first argument and callback as second.

We need to statement for compile a test. First a expect statement which is test assertion and other done function which notice the framework to completion of test. We can do many types of assertions

assert().toBe()
assert().toBeDefined() AND assert().toBeUndefined()
assert().toBeFalsy() AND assert().toBeTruthy()
assert().toBeNull()
assert().toEqual()
assert().toMatch()
assert().toThrow()

AND More....

Let we write test for previously REST APIs. Create a file called users.spec.js in spec folder.

var request = require("request");

var base_url = "http://localhost:3000/users"

let User = {
   _id:1,
   name:'',
   email:'',
   password:''
};

describe("Users List API Exists", function() {
     describe("GET /users", function() {
         it("returns status code 200", function(done) {
             request.get(base_url, function(error, response, body) {
             expect(response.statusCode).toBe(200);
             done();
         });
    });
 });

Above test check whether List API is available, It verify this by checking response status code is equal to 200 or not. Add another test to inner describe

it("API Response should be valid json", function(done) {
    request.get(base_url, function(error, response, body) {
        expect(() => {
            JSON.parse(body);
        }).not.toThrow();
        done();
    });
 });

Above test check if response is valid json or not. When invalid json as response return the native JSON parse function throw error which handled by expect ” not -> toThrow”. So assertion failed while in case of valid json assertion passed.

it("API Response should be valid array of user objects", function(done) {
     request.get(base_url, function(error, response, body) {
        let users = JSON.parse(body);
        const userRows = users.map((userRow) => {
            expect(JSON.stringify(Object.keys(User).sort()) ===     JSON.stringify(Object.keys(userRow).sort())).toBeTruthy();
        });
        done();
    });
 });

Above test goes further more and check return fields is valid. This test can be ignored in case of no restriction for fields returned in response.

I will discuss more on jasmine on API testing on further articles.

All code is hosted on Github

REST using Node/Express & Mongoose

NodeJS is fast growing language in today environment. For web their are several frameworks but Express web framework  is most used framework for web development in node js.

So how to make a sample Rest API in express / Node JS ?

First setup express using npm. So we use following commands to get npm init & require packages install.

# add package json
$ npm init

$ npm install --save express 
$ npm install --save mongoose body-parser

Above commands install express framework in node modules. Then it install http request parser package plus ODM package for mongo db called mongoose. Now it is time to do some coding. First create main application file app.js & put following code.

var express = require('express');
var app = express();
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');


// var UserController = require('./controllers/UserController');
// app.use('/users', UserController);

var port = process.env.PORT || 3000;
var server = app.listen(port, function() {
      console.log('Express server listening on port ' + port);
});

module.exports = app;

Update package.json to set tell about main script

"scripts": {
       "start": "node app.js"
 }

You can run this code by

$ npm start

Which start the server at 3000 port. You can check http://localhost:3000 which show “Cannot GET /” because we did not setup router. So we add a User Module. for this we need to add controller & model. So create two directories controllers & models for better code maintaining.  Add Following mongoose based code in models/User.js file.

var mongoose = require('mongoose');
var UserSchema = new mongoose.Schema({
    name: String,
    email: String,
    password: String
});
mongoose.model('User', UserSchema);
module.exports = mongoose.model('User');

Now Setup controller file controllers/UserController.js which also work as router for User APIs.

var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
router.use(bodyParser.urlencoded({ extended: true }));

var User = require('../models/User');

router.post('/', function (req, res) {

    User.create({
        name : req.body.name,
        email : req.body.email,
        password : req.body.password
    },
    function (err, user) {
        if (err) return res.status(500).send("There was a problem adding the information to the database.");
        res.status(200).send(user);
    });

});

// RETURNS ALL THE USERS IN THE DATABASE
router.get('/', function (req, res) {

    User.find({}, function (err, users) {
        if (err) return res.status(500).send("There was a problem finding the users.");
        res.status(200).send(users);
     });

});

// RETURNS USER DETAILS IN THE DATABASE
router.get('/:id', function (req, res) {

    User.findOne({"_id":req.params.id}, function (err, users) {
        if (err) return res.status(500).send("There was a problem finding the users.");
        res.status(200).send(users);
    });

});

// UPDATE USER DETAILS IN THE DATABASE
router.put('/:id', function (req, res) {

    User.update({"_id":req.params.id}, {
        name : req.body.name,
        email : req.body.email,
        password : req.body.password
    }, function (err, users) {
        if (err) return res.status(500).send("There was a problem finding the users.");
        res.status(200).send(users);
    });

});

// DELETE USER FROM THE DATABASE
router.delete('/:id', function (req, res) {
    User.remove({"_id":req.params.id}, function (err, users) {
        if (err) return res.status(500).send("There was a problem finding the users.");
        res.status(200).send(users);
     });

});

module.exports = router;

Now we have out two user APIs ready for insert a single record ( POST ) & get all records ( GET ). But still we need to register router with app, So uncomment lines in app.js

var UserController = require('./controllers/UserController');
app.use('/users', UserController);

Now we have http://localhost:3000/users working as POST & GET method for our APIs. We can test it by invoking respective methods via CURL CLI.

$ curl http://localhost:3000/users
$ curl -X POST -d 'email=kuldeep@gmail.com&name=Kuldeep&password=kamboj' http://localhost:3000/users

$ curl http://localhost:3000/users/5a47d942cb4f00c95de8f511

$ curl -X PUT -d 'email=kuldeepk@gmail.com&name=KuldeepK&password=kamboj' http://localhost:3000/users/5a47d942cb4f00c95de8f511

$ curl -X DELETE  http://localhost:3000/users/5a47d942cb4f00c95de8f511

 

leaflet maps with websocket/mqtt integration

Leaflet (http://leafletjs.com) is a javascript library for maps. It have lot of options for maps. Let we setup & try this.

You can download and configure directly as given examples, I choose option with yarn.

$ mkdir client

$ cd client

$ yarn add leaflet

Above command create node_modules folder in current directory & download leaflet and add into this.

Then write code html/javascript map code for leaflet map

<link rel="stylesheet" href="node_modules/leaflet/dist/leaflet.css">
 < script src="node_modules/leaflet/dist/leaflet.js" type="text/javascript"></ script>

< script type="text/javascript">

var map = L.map('map').setView([28.7041, 77.1025 ], 12);

L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y} png', {
 attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
 }).addTo(map);

L.marker([ 28.7041, 77.1025 ]).addTo(map)
 .bindPopup('Marker Here')
 .openPopup();

</ script>

Above code successfully show the map centered at new delhi, india. It also have a marker set with info popup.

This is simple case of map with marker and info popup, But some time we need to show some real time data. Like add marker on fly when new location updated. We may have lot of solutions for achieving this. One good solution to use Web Socket Protocol get/update data.

Let first set our Data Sender. I use MQTT Mosquitto broker & php script for achieving this. MQTT protocol work on pubsub model. So our server php script work as publisher while js application would work as subscriber.

But first we would need MQTT Broker. Mosquitto is recommended broker. on ubuntu ( or other deb based systems ) we need following commands to install mosquitto.

$ sudo apt-get install mosquitto mosquitto-clients

Also create a custom mosquitto config file at /etc/mosquitto/conf.d/mosquitto.conf & put following setting into it.

port 1883
protocol mqtt

listener 9001
protocol websockets

autosave_interval 10
autosave_on_changes false

Above setting setup the mqtt ( for publish ) port to 1883, & 9001 port for subscribe. Restart mosuitto service.

$ service mosquitto restart

We may test subscribe/publish with inbuilt commands

# Test Subscriber
$ mosquitto_sub -h localhost -t test

Here we are subscribing on localhost on topic “test”

# Test Publisher
$ mosquitto_pub -h localhost -t test -m "hello world"

Here we are publishing message “hello world” on broker on localhost on topic “test”

Now we setup php script. We use dependancy solver composer for install script dependencies. You can download composer.phar from https://getcomposer.org.

$ mkdir server

$ cd server

$ php composer.phar init

$ php composer.phar require bluerhinos/phpmqtt dev-master

Above command create vendor folder and install package phpmqtt into it. This is php package for mqtt.

Then create php script for publish mqtt data let called it publish.php & put following code into it.

require("vendor/autoload.php");
 use Bluerhinos\phpMQTT;
 $server = "localhost"; // change if necessary
 $port = 1883; // change if necessary
 $username = ""; // set your username
 $password = ""; // set your password
 $client_id = "mqtt-publisher"; // make sure this is unique for connecting to sever - you could use uniqid()

$coords = [
 [ 28.6442033, 77.1118256, 'Location 1' ],
 [ 28.5501396, 77.1882317, 'Location 2' ],
 [ 28.6359866, 77.2608032, 'Location 3' ],
 [ 28.6805603, 77.1991786, 'Location 4' ]
 ];
 $mqtt = new phpMQTT($server, $port, $client_id);
 if ($mqtt->connect(true, NULL, $username, $password)) {
    for($i=0;$i<count($coords);$i++) {
       $mqtt->publish("map/coordinates", json_encode($coords[$i]), 0);
       sleep(5);
    }
    $mqtt->close();
 } else {
    echo "Time out!\n";
 }

Above script connect to mqtt broker and then some latitude/longtitude after every 5 seconds. Real applications can build their logic for publish data on actual moment.

Now we make changes in our client script to subscribe mqtt, but first install mqtt packge for javascript.

$ cd client

$ yarn add paho-mqtt

Now time to change client script.

<link rel="stylesheet" href="node_modules/leaflet/dist/leaflet.css">http://node_modules/leaflet/dist/leaflet.js
< script src="node_modules/paho-mqtt/paho-mqtt-min.js" type="text/javascript">< /script>

< script type="text/javascript">

var map = L.map('map').setView([28.7041, 77.1025 ], 12);

L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
 attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
 }).addTo(map);

document.addEventListener('DOMContentLoaded', function() {
   mqtt_init();
}, false);

function mqtt_init() {
    // Create a client instance
    client = new Paho.MQTT.Client('localhost', 9001, "mqtt-spublisher");

   // set callback handlers
   client.onConnectionLost = onConnectionLost;
   client.onMessageArrived = onMessageArrived;

   // connect the client
    client.connect({onSuccess:onConnect});

   // called when the client connects
   function onConnect() {
    // Once a connection has been made, make a subscription and send a message.
      console.log("onConnect");
      client.subscribe("map/coordinates");
   }

   // called when the client loses its connection
   function onConnectionLost(responseObject) {
       if (responseObject.errorCode !== 0) {
          console.log("onConnectionLost:"+responseObject.errorMessage);
       }
    }

    // called when a message arrives
    function onMessageArrived(message) {
       console.log("onMessageArrived:" + message.payloadString);
       msg = JSON.parse(message.payloadString);
       L.marker([msg[0], msg[1] ]).addTo(map)
          .bindPopup(msg[2])
          .openPopup();

    }
 }

< /script>

 

When we publish our serve script, We see marker coming after duration (5 seconds ), which can become effective real time solution for maps.

Full code can be found at https://github.com/kuldeep-k/leaflet-mqtt

 

color Shades jQuery Plugin

colorShades is a jQuery plugin developed by me. It generate a html/css component for showing color shades for selected color for html input container.

Following code is needed to show widget.

$(field).colorShades({
   l_items: LIGHTER_SHADES_COUNT,
   r_items: DARKER_SHADES_COUNT,
   step: STEPS,
   base_color: BASE_COLOR,
   onSelect : CALLBACK
});

Exmaple :

$('#fieldId').colorShades({
   l_items: 10,
   r_items: 10,
   step: 3,
   base_color: '#FF0000',
   onSelect : function(color) {
       console.log('Selected Color '  + color);
   }
});

BASE_COLOR is hex color code for color which shades are needed
LIGHTER_SHADES_COUNT is color shades lighter than base color.
DARKER_SHADES_COUNT is color shades darker than base color
STEPS define the how much color change during next palette color. More steps means bigger change.
CALLBACK set the custom functionality on selection of color.

Screen Shot

color-shades-demo
Project Home Page : https://github.com/kuldeep-k/colorShades

Note : Plugin requires following 3rd party libraries.

jQuery
TinyColor

Composite key type duplicate key check with ZF2 Doctrine

Their are instances when we need to add some composite keys in our DBs. Then we also need a check on application side too. This is also same as duplicate check on multiple fields.

In ZF2, we know about Zend\Validator\Db\RecordExists & Zend\Validator\Db\NoRecordExists combo for duplicate check on database side (Zend DB). Their are also respective relative in doctrine called DoctrineModule\Validator\ObjectExists & DoctrineModule\Validator\NoObjectExists. They do the same job as Zend DB counter part with one caveat.

They do not support multiple fields when work with InputFilters. You can pass array but that gave error "zf2 Provided values count is 1, while expected number of fields to be matched is 2". The solution are using your custom validator.

I tried here to write a Validator Plugin which extends DoctrineModule\Validator\NoObjectExists and have support for multiple fields. See implementation code .


        $inputFilter->add($factory->createInput(array(
            'name' => 'studentId',
            'required' => true,
            'filters' => array(
                array('name' => 'StripTags'),
                array('name' => 'StringTrim'),
            ),
            'validators' => array(
                array(
                    'name' => 'Student\Validate\NoObjectExists',
                    'options' => array(
                        'object_repository' => $this->getObjectManager()->getRepository('Student\Entity\Student'),
                        'fields' => array('studentId', 'class'),
                    )
                )
            ),
        )));
        

Validator Plugin Code are as :


    namespace Student\Validate;

    use DoctrineModule\Validator\NoObjectExists as DoctrineModuleNoObjectExists;

    class NoObjectExists extends DoctrineModuleNoObjectExists
    {
        protected $messageTemplates = array(
            self::ERROR_OBJECT_FOUND    => "An object matching combination of fields was found",
        );

        public function isValid($value, $context = null)
        {
            $valueArray = array(); 
            foreach($this->fields as $name => $val)
            {
                $valueArray[] = $context[$val];
            }    
            $value = $this->cleanSearchValue($valueArray);
            
            $match = $this->objectRepository->findOneBy($value);
            
            if (is_object($match)) {
                $this->error(self::ERROR_OBJECT_FOUND, $value);

                return false;
            }

            return true;
        }
    }
      

Further link can be found at : https://github.com/kuldeep-k/zf2doctrine/blob/master/module/Student/src/Student/Validate/NoObjectExists.php

PHP 5.4 new features

PHP have introduced lot of interesting features in last few major versions. Some are obviously inspired from latest programming trends & from other languages. But these features make php more elegant and promising to code. Now I will discuss some of features in php version 5.4 I liked in following sections.

  • Short Array Syntax
  • Binary Numbers
  • Class::{expr}() and (new foo)->bar()) syntax.
  • Traits
  • Array Dereferencing

Short Array Syntax

This is my personal favorite feature. PHP have long history for define array through php function like this

$single_level = array(1, 2, "a" => "bcd");
$multi_level = array('first' => array(1, 2), 'second' => array(3,4), 'third' => array('3f' => array(5,6), '3s' => array(7,8)));

Not we have short syntax which eliminate the using array keyword using more mainstream operator for this.

$single_level = [1, 2, "a" => "bcd"];
$multi_level = ['first' => [1, 2], 'second' => [3,4], 'third' => ['3f' => [5,6], '3s' => [7,8]]];

Binary Numbers

PHP have support for octal and hexdecimal numbers for long time. But same privilege is not available for binary numbers. functions like decbin & bindec is only deal with string representation for binary numbers. Now we have binary number support they can be defined like.

$bin = 0b11011;

See 0b prefix which define for binary number. We already have prefix 0 and 0x for octal and hexadecimal repectively.

Class::{expr}()

If we need to call dynamic method for a class in earlier versions we something similar code.

class A 
{
    public static function functA()
    {
        echo "call A".PHP_EOL;
    }
    public static function functB()
    {
        echo "call B".PHP_EOL;
    }
}

$vars = array('A, 'B');
foreach($vars as $var)
{
    $c = 'funct'.$var;
    A::$c();
}

Now in 5.4 version instead of variable for method name we can code like

(new foo)->bar())

If we need to call a method for a class in earlier versions we something similar code.

class A 
{
    public $var = 10;
    public function methd()
    {
        echo $this->var.PHP_EOL;
    }
}

$a = new A();
$a->methd();

Now in 5.4 version instead of variable for method name we can code like this

(new A)->methd();

Like previous example this one too eliminate the use of variable for just one method calling.

Traits

I write a separate blog for introduce trait at https://kuldeep15.wordpress.com/2015/03/17/php-traits/

Array De-referencing

PHP provide a way to avoid creating variable when we need to access a particular member of array, specially when we accessing data dirtecly returned from function.

In previous versions :

function foo
{
    return array("a" => "First", "b" => "Second");
} 

$a = foo();
echo $a[1];

Using array de-referencing

function foo
{
    return array("a" => "First", "b" => "Second");
} 

echo foo()[1];

You can also use it for some special cases like below.

$str = "A,B,C,D,E";
echo explode(',',$str)[2];

In further articles I will explore interesting features from 5.5 & 5.6

PHP Traits

Traits are a new phenomenon in languages which do not support multiple inheritance. PHP also not directly support multiple inheritance while interface can be used to simulate but due to their abstract behavior, they are less usefull when we need functionality from two or more parent class into child class and we want to through inheritance.

Here Traits are introduced. They do exactly what multiple inheritance do, And while take care of method collision.

See following example in PHP without trait.

class Phone
{
    public function ring()
    {
    }
    public function message()
    {
    }
} 

class Computer
{
    public function email()
    {
    }
    public function surf()
    {
    }
    public function chat()
    {
    }
} 

class Smartphone extends Phone
{

}

We can not inherit the functionality of Computer into Smartphone class here. As computer class is already defined and user in another world we can not convert it into interface. So we need to make Computer interface for Smartphone class need to reimplement which duplicate Computer class structure.

interface ComputerInterface
{
    public function email();
    public function surf();
    public function chat();
}

class SmartPhone  extends Phone implements ComputerInterface 
{
    public function email()
    {
        // Copy implement here from computer class
    }
    public function surf()
    {
        // Copy implement here from computer class
    }
    public function chat()
    {
        // Copy implement here from computer class
    }
}

As we see this is not efficient way some times. So we need to use design patterns to resolve this problem. But trait resolve this problem in language itself.

trait Phone
{
    public function ring()
    {
    }
    public function message()
    {
    }
    public function login()
    {
    }
    public function logout()
    {
    }
} 

trait Computer
{
    public function email()
    {
    }
    public function surf()
    {
    }
    public function chat()
    {
    }
    public function login()
    {
    }
    public function logout()
    {
    }
}

class SmartPhone
{
    use Phone, Computer{
        Phone::login insteadof Computer;
        Computer::logout insteadof Phone;
    }
}

$smart = new SmartPhone();
$smart->login();
$smart->email();
$smart->ring();
$smart->logout();

Here we also see how trait handle same method name collision. Their are more functionality similar to classes available in trait like inheritance and abstract methods.

See (http://php.net/manual/en/language.oop5.traits.php)

Programmer wannable attitude

Well, Grasshopper, or Unschooled Acolyte, or whatever your title of choice may be…

You did not hear this from me.

But most developers belong to the Church of Pain and we pride ourselves on our arcane talents, strange cryptic mumblings and most of all, the rewards due the High Priesthood to which we strive to belong.

Let me put it bluntly. Some of this very complicated logic is complicated because it’s very complicated. And pretty little tools would do both the complexity and us injustice, as high priests or priests-in-training of these magical codes.

One day we will embrace simple graphical tools. But only when we grow bored and decide to move on to higher pursuits of symbolic reasoning; then and not a moment before will we leave you to play in the heretofore unimaginable sandbox of graphical programming tools. Or maybe we’ll just design some special programs that can program on our behalf instead, and you can blurt out a few human-friendly (shiver) incantations, and watch them interpret and build your most likely imprecise instructions into most likely unworkable derivative codes. Or you can just take up LOGO like they told you to when you were but a school child in the… normal classes.

Does that answer your impertinent question?

Comes from http://ask.slashdot.org/comments.pl?sid=4766093&cid=46191783

procedural MVC in php

Well I am reading some question on http://programmers.stackexchange.com/questions/184664/mvc-pattern-on-procedural-php regarding procedural MVC in php. Then I am thinking why it should not be possible? After all MVC is about architecture, You can make good architecture also in procedural programming. You just need to design proper architecture. As I checkout on MVC Frameworks, their are some common terms like

  • Bootstrap script, which initializing system, core services, routers.
  • Controllers
  • Models
  • Views

Also library, helpers are available depend on project wise.

Now I am giving you some light on, How a MVC (very basic of course ) can be built on following style.

Architecture

Project Root
    config
        config.php
    lib
        core.php
    controllers 
        UserController.php
        BaseController.php
    models
        User.php
    views
        user 
            index.php
        base 
            welcome.php
    resources
        css
            style.css

config.php Sample Code :

define('MODEL_DIR', 'models');
define('VIEW_DIR', 'views');

$config = array (
    'default_module' => 'base', 
    'default_action' => 'index',
);

lib/core.php Sample Code :

function safe($param) {
    return addslashes($param);
}

function render($file, $data)
{
    $layout_file = VIEW_DIR.'/layouts/layout.php';
    ob_start();
    include_once($file);
    $content = ob_get_clean();
    include_once($layout_file);
}

Bootstrap index.php Sample Code :

Let Request url is like /index.php?module=user&action=index

require_once('config/config.php');
require_once('lib/core.php'); // For some core functions like render
//require_once('lib/db.php');   // For DB Abstraction [ Later Improvement ] 

$module = isset($_REQUEST['module'])?safe($_REQUEST['module']):$config['default_module'];
$action = isset($_REQUEST['action'])?safe($_REQUEST['action']):$config['default_action'];

$controller_file = 'controllers/'.ucfirst($module).'Controller.php';
if(!file_exists($controller_file))
{
    trigger_error('Invalid Controller');
    exit;
}
require_once($controller_file);
$function = strtolower($module).'_controller_'.$action;
if(!function_exists($function))
{
    trigger_error('Invalid Controller Action');
    exit;
}
call_user_func($function, $_REQUEST);

BaseController.php Sample Code :

function base_controller_index($request)
{
    render(VIEW_DIR.'/base/welcome.php', array());
}

UserController.php Sample Code :

function user_controller_index($request)
{
    require_once(MODEL_DIR.'/User.php');
    $data = user_model_list($request);
    render(VIEW_DIR.'/user/index.php', $data);
}

function user_controller_add($request)
{
}

function user_controller_edit($request)
{
}

function user_controller_view($request)
{
}

Model User.php Sample Code :

function user_model_list($request)
{
    return array(
        array('name' => 'test', 'sname' => 'test1', 'city' => 'testc'),
        array('name' => 'abc', 'sname' => 'xyz', 'city' => 'mno'),
    ); 
}

function user_model_add($request)
{
}

function user_model_edit($request)
{
}

function user_model_view($request)
{
}

Layout file views/layouts/layout.php Sample Code :

<html>
<head>
<link rel=’stylesheet’ href=’resources/css/style.css’ type=’text/css’ media=’all’ />
<head>
<body>
<div><h1>Logo</h1></div>
<div><h2>Heading</h2></div>
<div class=”content”>
<?php echo $content ?>
</div>
<body>
</html>

View views/base/welcome.php Sample Code :

<i>Welcome</i>
<p>
<a href=”?module=user&action=index”>User Listing Page</a>
</p>

View views/user/index.php Sample Code :

<table class=”listing”>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>City</th>
</tr>
<thead>
<tbody>
<?php foreach($data as $row) { ?>
<tr>
<td><?php echo $row[‘name’] ?></td>
<td><?php echo $row[‘sname’] ?></td>
<td><?php echo $row[‘city’] ?></td>
</tr>
<?php } ?>
<tbody>
</table>

Sample code could be found at https://github.com/kuldeep-k/procMVC