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 :


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

Mix Object:

    "username": "zainabed",
    "first_name": "Zainul",
    "country": "India",
    "hobby": [

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


Thursday, October 23, 2014

Doctrine 2 Tutorials: Installation and Configuration

This tutorial post will help you to install Doctrine2 inside your PHP project and configure it so that you can use it's features in plain PHP project.

This post illustrates installation of Doctrine2 using Composer.


First create your project directory

 mkdir zainabed   

 cd zainabed

now create composer.json

vi composer.json

then add following repository information.

    "require": {
        "doctrine/orm": "*"

Now you are ready to install it via composer, but first we need to install composer into you machine.

curl -sS | php

Then initiate following command to install Doctrine2

php composer.phar install

composer creates "autoload.php" file which helps you to autoload all PHP classes of Doctrine2 ORM project.


First create configuration file configuration.php for Doctrine2 and include autoload.php inside it.


// configuration.php

// Include Composer Autoload 
require_once "vendor/autoload.php";

Then create database configuration details, like database name, username ,password.

// database configuration

$databaseParams = array(
    'driver'   => 'pdo_mysql',
    'user'     => 'root',
    'password' => '',
    'dbname'   => 'zainabed',

Then specify Entity path where you want to store all ORM Entities.

//entity path
$entityPath = array("src/Entity");

Now create Entity Manager object.
Entity Manager is center source of ORM which handle interaction between Entities and Database.

//annotation configuration
$config = Setup::createAnnotationMetadataConfiguration($entityPath, false);

//entity manager object
$entityManager = EntityManager::create($databaseParams, $config);

now you are ready to use Doctrine2 inside your PHP project.

following is complete configuration example which also includes configuration based on XML and YML.


// configuration.php

// Include Composer Autoload 
require_once "vendor/autoload.php";

use Doctrine\ORM\Tools\Setup;
use Doctrine\ORM\EntityManager;

// database configuration
$databaseParams = array(
    'driver'   => 'pdo_mysql',
    'user'     => 'root',
    'password' => '',
    'dbname'   => 'zainabed',

//entity path
$entityPath = array("src/Entity");

//annotation configuration
$config = Setup::createAnnotationMetadataConfiguration($entityPath, false);

//entity manager object
$entityManager = EntityManager::create($databaseParams, $config);

//xml configuration
//$xmlEntituPath = array("/path/to/xml-mappings");
//$config = Setup::createXMLMetadataConfiguration($xmlEntituPath, false);
//$entityManager = EntityManager::create($databaseParams, $config);

//yml configuration
//$ymlEntityPath = array("/path/to/yml-mappings");
//$config = Setup::createYAMLMetadataConfiguration($ymlEntityPath, false);
//$entityManager = EntityManager::create($databaseParams, $config);

Doctrine 2 is now configured and ready to use.


Thursday, October 16, 2014

Twig Tutorials: Install and Configure

In this tutorial we will see how to install Twig inside your PHP project and then configure it so that we can create use Twig template inside our PHP web application.

later we see a simple Twig template example which will display "Welcome to Twig template" message.

lets see each step one by one.


we can install Twig template via Composer, Git or from PEAR.

in this tutorial post we will install Twig using Composer.

for that we need to create "composer.json" file.

    "require": {
        "twig/twig": "1.*"

the from console run following command.

  php composer.phar install   

this command will install Twig library.


To use Twig template we need configure it first, for that we will create index.php file which will setup Twig autoloader and generate the Twig environment.

using this Twig environment we will render Twig template

include __DIR__ . "/vendor/twig/twig/lib/Twig/Autoloader.php";

//register autoloader


//loader for template files

$loader = new Twig_Loader_Filesystem('templates');

//twig instance

$twig = new Twig_Environment($loader, array('cache' => 'cache'));

//load template file

$template = $twig->loadTemplate('index.html');

//render a template

echo $template->render(array('title' => 'Welcome to Twig template'));

now we will create "template.html" file inside template folder.




    <h1>{{ title }}</h1>



and you will get following output when you run index.php file in localhost

That's it, we are done with Twig installation and configuration process.

Source Code

Download source code from this Github link

Tuesday, October 14, 2014

Generate SSH Public Key for GitHub and Bitbucket

ssh key github bitbucket

This post demonstrate how to generate SSH private and public key with simple steps and help you to add public key inside your GitHub and Bitbucket account.

But first why we need this SSH public key?

Whenever you access or do some Git operation on remote repository using HTTPS connection from your local machine, you need to authenticate yourself first using username and password.

It looks simple earlier, but later becomes headache.

SSH connection helps us to authenticate using public and private keys, that we generate only once, later we don’t need to authenticate, SSH will do this behalf of us.

But how does it works?

SSH authenticate you using an identity. And this identity is combination of private, public key.

Private Key resides in your local machine and public key inside your GitHub or Bitbucket account.

When you access Git repository, SSH combines these two keys and authenticates you.
To use SSH you need to install it first. I assumed that you have already installed it, if not 
then please visit and install SSH to your local machine.

Generate private-public keys

Us following steps to generate private and public key, later copy public key and add it in your GitHub and Bitbucket account.

Open terminal and type following command


It will ask location for key files, hit Enter to select default location

Then it will ask passphrase (password), you can type your password or cant keep it empty

It will ask re-passhprase

once done, keys get generated and get saved inside provided location. 
Here is sample output of ssh-keygen operation.

Then add your key to the ssh-agent.
  ssh-add ~/.ssh/id_rsa    

Later we need to add public key to GitHub and Bitbucket account. To do so we need get 
content of public key, this resides inside ~/.ssh path.

  cat ~/.ssh/     

Now copy this key and visit GitHub or Bitbucket to add it into your account.


Open a browser and log into your GitHub account.

  • Select setting icon from top right corner of menu bar.
  • Then select “SSH keys” from left side panel
  • Now add new public key by selecting “Add SSH key” button. It will open a panel to enter public key.
  • Add label for public key and then add copied public key inside key area.
  • Now finish this process by clicking "Add key" button.

That’s it, you done with GitHub.


Open a browser and log into your Bitbucket account.

  • Select Avatar->Manage Account from the application menu.
  • Under Security section Click SSH keys.
  • Then click Add key button. It will prompt a dialog to add public key.
  • Add label for public key and then add copied public key inside key area.
  • Now finish this process by clicking Add key button.

That’s it, you done with Bitbucket.

Thursday, October 2, 2014

Symfony Tutorials: Event Dispatcher

Symfony Tutorials: Event Dispatcher

Symfony EventDispatcher is object which interacts with different set of objects when certain event happens.

To illustrate Event Dispatcher definition let’s consider the online shopping website example.

suppose you want to purchase a mobile from online shopping website , but unfortunately that mobile is out of stock.

Then you subscribe into online shopping website for this mobile availability.

When mobile comes in stock, online shopping website notifies you about mobile phone’s availability via email.

In above scenario

  • you are the Event Listener / Event Subscriber
  • mobile availability is Event
  • online shopping website is Event Dispatcher.

Symfony EventDispatcher works in same manner.for example, whenever there is HTTP request, Kernel creates a request object and it dispatches an event kernel.request.

Whoever subscribes to kernel.request event gets notified.

So here you might be having few questions in my mind.

What is Event?

Event object describe what event is and add some additional information so that its listener or subscriber can get enough information about event.

What is EventDispatcher?

EventDispatcher is central object which dispatches the event to all its listener or subscriber.
EventDispatcher maintains the list of all listeners of a particular Event.

use Symfony\Component\EventDispatcher\EventDispatcher;

$dispatcher =new EventDispatcher();

What is Event Listener?

Listener is a object which performs a task whenever a associated event happens. 
But first we need to attach listener to Event Dispatcher for a particular event.

$listener=new MobileAvailabilityListener();

Considering Online Shopping Store example let’s create a custom event and dispatch this event.

Here we want to create mobile availability event which get dispatched whenever mobile is available.

First we create static event class which holds event name and its instance information

Static Event Class

final class MobileEvents
     * The event is thrown each time when mobile 
  * is available in store
     * The event listener receives an
     * Acme\StoreBundle\Event\MobileAvailableEvent instance.
     * @var string

Later, create actual event object.

Symfony uses Symfony\Component\EventDispatcher\Event class.

This class wont give us enough information about mobile availability therefor we need to subclass it and add additional information.

namespace Acme\StoreBundle\Event;

use Symfony\Component\EventDispatcher\Event;
use Acme\StoreBundle\Mobile;

class MobileAvailableEvent
  protected $mobile;

  public function__construct(Mobile $mobile)

  public function getMobile()
    return $this->mobile;

Later, create event listener, which sends emails to user regarding availability of the mobile phone.

use Acme\StoreBundle\Event\MobileAvailableEvent;

class MobileAvailabilityListener
  // ...

  public function sendEmailToUsers(MobileAvailableEvent $event)
     // ... send email to users

Now all is set, let’s attach this listener to the dispatcher. And dispatch the event.
use Symfony\Component\EventDispatcher\EventDispatcher;
use Acme\StoreBundle\Event\MobileAvailableEvent;
use Acme\StoreBundle\Event\MobileAvailabilityListener;
use Acme\StoreBundle\Entity\Mobile;
$dispatcher = new EventDispatcher(); // attach listener $listener = new MobileAvailabilityListener(); $dispatcher->addListener(MobileEvents::MOBILE_AVAILABLE, array($listener, 'sendEmailToUsers')); //if mobile is available then dispatch the event
$mobile = new Mobile();
$event = new MobileAvailableEvent($mobile);
$dispatcher->dispatch(MobileEvents::MOBILE_AVAILABLE, $event);

This is a every basic example, you can create event for user registration process and can send confirmation email via event listener or can do  many things using Symfony Event Dispatcher.