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...