Wednesday, March 4, 2015

AngularJs Tutorials : Bootstrap


Every application starts with bootstrap process which initialize application and wire it other with dependencies and configurations.

AngularJs is not different from other application. It also starts application with bootstrap process.

Following operation happens inside AngularJs bootstrap process.

  1. Load application module.
  2. Create dependency injector and load dependencies.
  3. Compile HTML and create scope for application.

All these steps happens inside angular.js scripting file. therefore we need to include it first.
we can include it inside HEAD tag or at end of BODY tag.

Note:
Adding angular.js file at end of body tag will allow browser to load of HTML elements without any delay and afterwards load angular.js and begin bootstrapping process.

You can get angular.js source file from https://code.angularjs.org/


<script src=”https://code.angularjs.org/1.3.0/angular.js” type=”text/javascript”>

AngularJs bootstrap process happens on document ready event.


lets see the simple AngularJs example.


<html>
 <head>
    <title>Angular Application</title>
 </head>
 <body ng-app="myApp">
    <div ng-controller="myCtrl">
        <h3>{{title}}</h3>
    </div>

    <script src="https://code.angularjs.org/1.3.0/angular.js" type="text/javascript"></script>

    <script type="text/javascript">

        //angular module
        angular.module("myApp",[])
      

        //controller
        .controller("myCtrl", ["$scope", function($scope){
            $scope.title = "Angular Bootstrap Tutorial!"
        }])

    </script>

 </body>
</html>


Now lets look into AngularJs bootstrap process steps one by one.

  1. Load application module:

    AngularJs will look for module name which is associated with ng-app directive inside HTML page.


    <html ng-app="myApp" >
    …
    …
    


    Then Angular will load this module from JavaScript snippet.


    angular.module("myApp", []) 
    

  1. Create dependency injector and load dependencies

    After first step AngularJs will create injector and compiler objects. functionality of compiler object is listed in third step.
    Here injector object will look for dependency of application module. In above example we have not specify any dependency.
    Following example illustrate module dependency


    angular.module("myApp",[ "ngResource"])
    


    These dependencies are nothing but angular modules. injector load this modules and allow them to be used inside angular application.

    Services can also be injected on fly inside application controller or application services.


    .controller("myCtrl", ["$scope", function($scope){
      $scope.title = "Angular Bootstrap Tutorial!"
    }])
    

    in above example $scope is injected by injector inside controller and we can use it inside controller.
  2. Compile HTML and create scope for application.

    Inside last step AngularJs compiles HTML elements using compiler object then creates scope for application and bind rootScope to html element where we have specified ng-app.
    In above example ng-app is specified inside body tag which means rootScope is attached to body tag and all template logic get applied on this body tag.


Above scenario illustrates automatic bootstrapping process. but some time you may require to manually bootstrap AngularJs application where you need to perform some custom JavaScript task before initiating AngularJs application.

Following script snippet shows manual bootstrapping process.


// document ready event
angular.element(document).ready( function() {

    // bootstrap document with myApp module
    angular.bootstrap(document, ["myApp"])

})


As stated earlier bootstrap happens on document ready event therefore you need to configure it first.
Then call angular.bootstrap function which will accept two parameters.

First parameter is html element e.g. document, html, body or particular div. this process is equivalent as specifying ng-app directive to HTML element.

Second parameter is AngularJs module name. in this case we have give myApp.

Note that you first need to add module scripting code then initiate bootstrap process otherwise bootstrap will throw error that unable to load given module.

With automatic or manual bootstrap, you are ready to create beautiful AngularJs application.


Read More...

Thursday, November 27, 2014

MongoDB Tutorials : Aggregation Framework



MongoDB Aggregation Framework groups set of documents together and performs certain operation on this grouped documents and returns results in the form of documents.
MongoDB aggregation answer to those query which requires grouping of documents.


Aggregation framework works on three type of model
  • Aggregation pipeline
  • Map Reduce
  • Single Purpose Aggregation Operations


Now let see how MongoDB Aggregation Framework works with simple example.

Suppose you are MongoDB application developer in a respected company and you have been given a MongoDB database that holds information about human population which is distributed according to cities and their states.

here is one sample document.


{
        "city" : "ACMAR",
        "loc" : [
                -86.51557,
                33.584132
        ],
        "pop" : 6055,
        "state" : "AL",
        "_id" : "35004"
}


for this tutorial collection name is zips.

on first day your manager come and asks you to calculate total population of state DC.

your simplest approach to solve above query would be find all documents which have DC as state. then iterate them one by one and add population to a variable.
here is the a sample script

MongoDB script 1

 var record = db.zips.find( { "state" : "DC"} )
 var sum = 0;
 record.forEach(function(rec){ sum = sum + rec.pop })
 print("Total population of State DC = " + sum)

Total population of State DC = 606900

This works fine and given task is done.
later, next day your manager comes and tells you to find total population of each states.

now this query is little tricky, but you would modify you first MongoDB script and make it is given below.

MongoDB script 2


 var states = db.zips.distinct("state")
 
 states.forEach(function(state){

   var records = db.zips.find({"state" : state});
   var sum = 0;

   records.forEach(function(record){
     sum = sum + record.pop;
   });

   print( state + " population: " + sum);
 });

yes, it will give you expected result. no doubt you are a good MongoDB developer.

but you have put extra efforts get result. it does not mean that you are not a good developer, rather you are not aware of MongoDB aggregation framework which produce expected result in one query.

following is aggregation query


db.zips.aggregate([ { "$group" : { "_id" : "$state", "population" : { "$sum" :
 "$pop" } }} ])
it will give you same result which in equivalent of second MongoDB script.
now let see how it works.

First look out the group clause of aggregate query.

db.zips.aggregate([ { "$group" : { "_id" : "$state" } } ])
 
 
it will group collections according to state



 
as documents are grouped now we can perform calculation on them like summation of population.


db.zips.aggregate([ { "$group" : { "_id" : "$state", "population" : { "$sum" :
 "$pop" } }} ])



hence you get expected result in one query using MongoDB Aggregation Framework.




Read More...

Sunday, November 2, 2014

PHP Tutorials : Autoload PHP Classes

This tutorials post will explain PHP autoloader and namespace concept using few basic question and answer regarding PHP autoload functionality along with some examples.

What is Autoloading in PHP?

PHP provides helper functions to include or import PHP files, if it has not been included before. if we use PHP autoload then we don't need to write require or include statement for each PHP class files.

Why we need auto loading?

It is a good question. why we need it, although we can write require or include statements whenever we need. As PHP has evolved using OOPs concept, we create more classes for our PHP project and create a separate PHP file for each single PHP class. Hence we increase the number of require or include statements. therefore we need some standard way to include each files rather specifying include statement by our self every time. that is why PHP has provided some useful methods to resolve this problem.

PHP Autoloading Methods

PHP uses two function, one is magic method __autoload and another is spl_autoload_register. each of these have their own benefit. they accept one parameter which turns into class name whenever we instantiate that class object. inside these method we could write our logic to load PHP class file.

What is difference between __autoload and sp_autload_resgister function?

__autoload method is magic method which means you can define it only once. therefore you would have only one logic to include PHP class files whereas spl_autoload_register is defined function which accept function name as parameter and we can define specified function with our logic. that mean we can have multiple implementation of inclusion of PHP files with help of spl_autoload_register.
e.g
<?php

/**
 * autoload method
 */
function __autoload($class)
{
  require $class.'.php';
}

//spl_autoload_register

/**
 * autoload method one
 */
function autoloadOne($class)
{
  require "/dir-one/".$class.".php";
}

/**
 * autoload method two
 */
function autoloadTwo($class)
{
  require "/dir-two/".$class.".php";
}

//register auto loader
spl_autoload_register("autoloadOne");
spl_autoload_register("autoloadTwo");

What is namespace?

PHP normally wont allow two class with same name. but later 5.3 introduce concept of namespace which create a ownership of class so that two different class can have same class name but with different ownership.

What is importance of namespace in autloading

when we autoload class we get a parameter into autload function. when you echo that parameter it will print that class name and namespace provides directory structure for classes.
e.g
<?php

namespace Module\User\Controller;
namespace Module\User\Entity;
namespace Module\User\Form;
namespace Module\User\Validator;

if we autoload above class then we will get whole namespace of that class along with class name e.g namespace_autoload.php
<?php

function __autoload($class)
{
  echo "class path = ".$class;
  die ;
}

new \Module\User\Controller();

// it will print
// class path = Module\User\Controller
with help of this information we can organize classes according to our project directory structure. let say you have following project structure

project
 |__Module
      |__User
          |__Controller
          |__Entity
          |__Form
 |
 |__autoload.php

then you can create PHP classes with namespace as



 project
 |__Module
     |__User
   |__Controller   \\ class : IndexController , namespace Module\User\Controller
          |__Entity   \\ class : User , namespace Module\User\Entity
          |__Form  \\ class : UserForm , namespace Module\User\Form
 |
 |__autoload.php
 
autoload.php
<?php

//include namespace

use Module\User\Controller\IndexController;
use Module\User\Entity\User;
use Module\User\Form\UserForm;

/**
 * Autload project files
 */
function __autoload($class)
{
  echo $class;
  require $class;
}

// instantiate classes
$controller = new IndexController();
//(it will print)  Module\User\Controller\IndexController and load this class

$user = new User();
//(it will print)  Module\User\Entity\User  and load this class

$userForm = new UserForm();
//(it will print) Module\User\Form\UserForm  and load this class
as you can see how namespace helps to organize project structure and autoload the classes.

What is difference between following two sets of statements

namespace autloading Direct include files

 use Module\User\Controller\IndexController;     require "Module\User\Controller\IndexController"; 
 use Module\User\Entity\User;       require "Module\User\Entity\User";
 use Module\User\Form\UserForm;           require "Module\User\Form\UserForm";

General difference is require statement accept full directory path where in case of namespace we can set logic to autoload PHP files with different directory structure and can minimize the namespace length. let see the example, suppose you have following directory for your project library files
project
 |
 |__vendor
 |
 |__lib
  |
  |__src
   |
   |__components
    |
    |__HTTP  //Request, Response classes
    |
    |__Controller  //BaseController classes
    |
    |__Form //BaseForm classes
 ..... many more files
using require statement need to write following code.
<?php

 require "/vendor/lib/src/components/HTTP/Request";
 require "/vendor/lib/src/components/HTTP/Response";
 require "/vendor/lib/src/components/Controller/BaseController";
 require "/vendor/lib/src/components/Form/BaseForm";
which is very lengthy and not properly organized with help of autoload and namespace we can reduce and class path and organize structure in much proper ways
<?php

define("LIB_PATH", "/vendor/lib/src/components");

use HTTP\Request;
use HTTP\Response;
use Controller\BaseController;
use Form\BaseForm;

/**
 *  autoload lib class files
 */
function __autoload($class)
{
  // set class path
  $class_path = LIB_PATH.$class;

  //include class file
  echo $class_path;
  require $class_path;
}

$request = new Request;
// (it will print)  /vendor/lib/src/components/HTTP/Request

$controller = new BaseController;
// (it will print)  /vendor/lib/src/components/Controller/BaseController

Summary


  • autoload helps to load all PHP classes of a PHP project.
  • namespace helps to organize your PHP classes
  • combination of autoload and namespace organize and load PHP project in standardized way.


Read More...

Saturday, October 25, 2014

JSON Tutorials : Getting Started


JSON is widely accepted text formatted structured data. JSON stands for "JavaScript Object Notation". In general JSON can represent 1. Object of database record. 2. Object to represent a list of HTML elements. 3. Result of search query. 4. Response of an Ajax call. Here you can see JSON is used in many different areas and for many different scenarios. This means it has simple data structure. most of programming languages adopt it and it can flow easily from one connection to another. You can find JSON office definition here JSON Official Site. JSON is represented by two structural types, which includes two primitive types. Structural types

Array: A sequential list of primitive data types between square brackets [ ]
Object: Collection of key, value pair stored inside curly braces { }, where value would be primitive data type

Primitive types:
There are two primitive types key and value. "key" should be string and "value (data type)" could be anything like integer, string , Boolean , empty or null. Lets see some example of JSON objects.

Array :

[
    "apple",
    "orange",
    "blackberry",
    "grape"
]
Object:

{
    "username": "zainabed",
    "first_name": "Zainul",
    "country": "India"
}


Mix Object:

{
    "username": "zainabed",
    "first_name": "Zainul",
    "country": "India",
    "hobby": [
        "reading",
        "programming",
        "sports"
    ]
}


JSON is widely accepted and used because
  • It is lightweight, that is why it is possible to transfer large set of data without exhausting internet bandwidth.
  • It is language independent, which means most of the programing languages have mechanism to accept or generate JSON objects, it doesn’t need extra functionality to make JSON objects compatible with other languages.
  • JSON can be as primary object for database system. it is used to store and read or perform CRUD operation on JSON which can be stored as documents. MongoDB is popular database system which based on JSON documents.
  • JSON can have Embedded documents as well, it helps to avoid expensive join operations on related documents. here rather using joins, one JSON documents can be embedded inside another.
  • JSON object can be used to represent HTML entities like list of user, tables or image gallery. AngularJs is most powerful tool to transform JSON to HTML.
  • JSON can also represent search result. search result could include search count, search title and description list , etc. all this can be included in a JSON object. Elasticsearch represent its search result in JSON object. as it is JSON object it can be used in any programming languages as result.
  • JSON play important role in drawing of charts. charts requires data set to create a particular chart and JSON object is perfect data model for it. D3 charts are always use JSON objects.
Frequently Asked Questions:

1: Can JSON starts with Array?
Answer: Yes, JSON can start with Array or Object, there is no such restriction.

2: What is the correct JSON content type for HTTP response?
Answer: Correct content type for JSON is application/json

3: Safely turning a JSON string into an object inside a JavaScript?
Answer: Following two function call will turn string to JSON object


jQuery.parseJSON( jsonString ); //Jquery

JSON.parse(jsonString); //plain JavaScript

Read More...