Wednesday, May 19, 2010

Setting up replication on postgresql9.0 beta

Eventually postgresql comes out with its inbuilt replication solution in 9.0 beta. Setting up of replication is quite simple. We will look at setting up a simple master-slave replication between two servers of postgresql.

The way replication works in postgres is that the master keeps on writing "write ahead log" files (also known as wal files). The slave can be configured to run either in recovery mode or hot standby. The difference being that in recovery mode the wal files require to be shipped using something like a cron. And the slave applies the wal files to its database. The problem here is that it is not smooth and the delay between master and slave can be big. The logic of hot standby is that the slave connects to the master and fetches the log files from master. And it applies those log files on its database. Here the lag between master and slave is not huge since the slave tries to keep up with the master. This is also known as streaming replication because the wal files are continuously shipped to the slave and applied there. There could be multiple slaves fetching wal files from master and applying to their own database. As opposed to mysql the slave here is readonly - it cannot be modified. It can be used only as read-only slave for select queries.

Lets look at deploying master-slave replication between two servers

Master server : 172.16.3.173
Slave server : 172.16.3.211

Step 1:
Install postgresql 9.0 on both servers. Simple steps for installation are
$ ./configure
$ make
$ make install
$ adduser postgres

Step 2:
Initialize the data directory on master. No need to initialize it on slave - since we will be copying the master directory to slave for starting replication.
$ mkdir /usr/local/pgsql/data
$ chown -R postgres.postgres /usr/local/pgsql/data
$ su - postgres
$ /usr/local/pgsql/bin/initdb -D /usr/local/pgsql/data

In case you are trying to create a slave of existing postgres database, you can simply skip these steps and install postgres on a slave machine - and not initialize the data directory on the slave machine.

Step 3:
Change config on master so that any slave is authorized connect to the master. Add the following line to pg_hba.conf of master.
$ vim data/pg_hba.conf
host    replication     postgres        172.16.3.211/22         trust
This says that 172.16.3.211 (the slave) is allowed to connect to master for replication without any password. Configure this for all slaves (if you plan to have multiple slaves).

Step 4:
Change parameters on the master postgresql for streaming replication.
$ vim data/postgresql.conf
# allow all ip addresses to connect to the master.
listen_addresses = '*'

# set wal_level for hot standby replication.
wal_level = hot_standby

# enable archiving to an archive directory accessible from the standby. Not required for streaming replication. But set it for "just in case" scenarios 
archive_mode = on
archive_command = 'cp "%p" /path/to/archive_directory/"%f"'

# set the number of concurrent slave connections
max_wal_senders = 5

# set the minimum no of WAL segments to be retained in the pg_xlog directory from where the slave can pick up the WAL segments.
# This prevents removal of WAL segments before they are shipped the slave.
wal_keep_segments = 32

Step 5:
Start postgres on primary/master server.

Step 6:
Create a backup of master and ship it to the slave server.
$ ./bin/psql -c "SELECT pg_start_backup('postgres',true)"
$ rsync -a /usr/local/pgsql/data postgres@172.16.3.211:/usr/local/pgsql/data
$ ./bin/psql -c "SELECT pg_stop_backup()"

Step 7:
Clean the data directory in slave and set replication parameters.
$ rm /usr/local/pgsql/data/postmaster.pid
Here the postgresql.conf is same as master, so just set the parameters required by slave.
$ vim /usr/local/pgsql/data/postgresql.conf
# disable archiving
archive_mode = off
# enable read-only queries on slave - during replication/recovery
hot_standby = on


Step 8:
Setup the parameters in recovery.conf required for streaming replication
$ vim recovery.conf
# shell command for copying log files back from the archive. Should not be required.
restore_command = 'cp -i /home/postgres/archive/%f "%p" </dev/null'
# enable standby
standby_mode = 'on'
# connection information for connecting to master
primary_conninfo = 'host=172.16.3.173 port=5432 user=postgres'
# stop streaming and enable the server to work in read/write mode, if this file is found.
# server keeps on polling for the trigger file and stops replication once this file is found. The server can then be used in read/write mode.
trigger_file = '/usr/local/pgsql9.0/data/stop.replication'



Step 9:
Start postgres on slave. It will start streaming replication between master and slave.
To check replication see if sender process is active on master
$ ps -ef | grep sender
postgres 12332 12158  0 10:13 ?        00:00:00 postgres: wal sender process postgres 172.16.3.211(41497) streaming 0/90149F0
postgres 16233  9474  0 11:36 pts/2    00:00:00 grep sender
On slave check if receiver process is working
$ ps -ef | grep receiver
postgres 27952 27945  0 10:12 ?        00:00:00 postgres: wal receiver process   streaming 0/9014974        
postgres 30354 23492  0 11:36 pts/0    00:00:00 grep receiver

That is it. Run a few DML/DDL queries on master and check if they are being replicated on slave. The lag between master and slave is not noticable.

Friday, April 09, 2010

An intro to Thrift

What is thrift - a software framework for scalable cross language service development. It combines software stack with a code generation engine to build services that work efficiently and seamlessly between C++, Java, Python, Ruby, Erlang, Perl, Smalltalk etc.

Thrift allows you to define data types and service interfaces in a simple definition file. Taking the definition file as input the thrift compiler generates code that can be used to easily build RPC clients and servers that communicate seamlessly across programming languages.

You can find all this stuff at http://incubator.apache.org/thrift/.

My intention here is to provide a step by step guide to installing and building simple services in java/php using thrift. Since till date there is no proper tutorial, this should be helpful.

To download thrift, you can either get it from http://incubator.apache.org/thrift/download/ or do

$ svn co http://svn.apache.org/repos/asf/incubator/thrift/trunk thrift
$ cd thrift

Installation steps

$ ./bootstrap.sh
$ ./configure
$ make
$ make install


thrift depends on c++ boost libraries. To install boost libraries on ubuntu do

$ sudo apt-get install libboost-dev libboost-doc libboost-thread-dev libboost-python-dev

or

$ sudo apt-get install libboost-*

One problem i ran into while doing "sudo make install" was

Error: JAVA_HOME is not defined correctly.
We cannot execute java

The solution to this is

$ su
$ <enter password>
$ export JAVA_HOME=/path/to/jdk
$ export ANT_HOME=/path/to/ant
$ export PATH=$JAVA_HOME/bin:$ANT_HOME/bin:$PATH
$ make install


It would install the required libraries for all supported languages.

Now lets try writing a very simple service using thrift and use php/java clients to communicate with the service.

First we need to create a thrift definition file.

$ mkdir test # create a separate working directory
$ cd test
$ vim time.thrift # paste the following code in time.thrift

namespace java tserver.gen  // define namespace for java code
namespace php tserver  // define namespace for php code

typedef i64 Timestamp

service TimeServer {  // define the service you want to implement
  Timestamp time(),   // define the funcionalities the service would provide.
            string date(),
            i64 multiply(1:i32 num1, 2:i32 num2),
}
Namespaces are the places where code would be generated - what we call package in java.

Create a separate directory to store source files

$ mkdir src
$ cd src
$ vim TimeServerImpl.java

Create a java source file for implementing the functions that we had defined in the time.thrift file. The name of the file is the Service name (as defined in the thrift file) followed by "Impl". Provide the body of the functions in this file.

package server;

import java.util.*;
import org.apache.thrift.*;
import tserver.gen.*;

class TimeServerImpl implements TimeServer.Iface
{
  public long time() throws TException
  {
    long time = System.currentTimeMillis();
    System.out.println("Current time : "+time);
    return time;
  }

  public String date() throws TException
  {
    Calendar now = Calendar.getInstance();
    String dt = now.get(Calendar.YEAR)+"-"+(now.get(Calendar.MONTH)+1)+"-"+now.get(Calendar.DAY_OF_MONTH)+" "+now.get(Calendar.HOUR_OF_DAY)+":"+now.get(Calendar.MINUTE)+":"+now.get(Calendar.SECOND);
    System.out.println(" date : "+dt);
    return dt;
  }

  public long multiply(int num1, int num2) throws TException
  {
    System.out.println("Got : "+num1+", "+num2);
    return num1*num2;
  }
}

$ vim Server.java

Create a file for providing the service. This program simply has a main function which binds the service to a particular port and makes the server ready to accept connections and provide response. This code will generally remain constant unless you want to provide additional functionality at server level.

package server;

import java.io.*;
import org.apache.thrift.protocol.*;
import org.apache.thrift.protocol.TBinaryProtocol.*;
import org.apache.thrift.server.*;
import org.apache.thrift.transport.*;
import tserver.gen.*;

public class Server
{
  private void start()
  {
    try
    {
      TServerSocket serverTransport = new TServerSocket(7911);
      TimeServer.Processor processor = new TimeServer.Processor(new TimeServerImpl());
      Factory protFactory = new TBinaryProtocol.Factory(true, true);
      TServer server = new TThreadPoolServer(processor, serverTransport, protFactory);
      System.out.println("Starting server on port 7911 ...");
      server.serve();
    }catch(TTransportException e)
    {
      e.printStackTrace();
    }
  }

  public static void main(String[] args)
  {
    Server srv = new Server();
    srv.start();
  }
}

$ vim TimeClient.java

And create a client which will connect to the server on the specified port and call the provided functions.
package client;

import java.net.*;
import org.apache.thrift.*;
import org.apache.thrift.protocol.*;
import org.apache.thrift.transport.*;

import tserver.gen.TimeServer.Client;

public class TimeClient {
  private void start(){
    TTransport transport;
    try {
      transport = new TSocket("localhost", 7911);
      TProtocol protocol = new TBinaryProtocol(transport);
      // this client depends on the client class in the gen-java/tserver/gen/TimeServer.java file
      // public static class Client implements TServiceClient, Iface
      Client client = new Client(protocol); 
      transport.open();
      long time = client.time();
      System.out.println("Time from server:" + time);
      String dt = client.date();
      System.out.println("Got date from server: "+dt);
      long res = client.multiply(30,100);
      System.out.println("Multiply from server: "+res);
      transport.close();
    } catch (TTransportException e) {
      e.printStackTrace();
    } catch (TException e) {
      e.printStackTrace();
    }
  }

  public static void main(String[] args) {
    TimeClient c = new TimeClient();
    c.start();
  }
}
Now lets move ahead and generate the thrift code. And compile everything.

$ thrift --gen java time.thrift
$ vim build.xml


Write a simple build.xml to build these files
<project name="tserver" default="tserver" basedir=".">
<description>Time Server Tutorial</description>

<property name="src" location="src" />
<property name="gen" location="gen-java" />
<property name="build" location="build" />
<property name="cpath" location="/usr/local/lib/libthrift.jar:/usr/local/lib/slf4j-api-1.5.11.jar" />

<target name="init">
<tstamp />
<mkdir dir="${build}"/>
</target>

<target name="compile" depends="init">
<javac srcdir="${gen}" destdir="${build}" classpath="${cpath}" >  
<compilerarg value="-Xlint:deprecation"/> 
</javac>
<javac srcdir="${src}" destdir="${build}" classpath="${cpath}:${gen}" >   
<compilerarg value="-Xlint:deprecation"/> 
</javac>
</target>

<target name="tserver" depends="compile">
<jar jarfile="tserver.jar" basedir="${build}"/>
</target>

<target name="clean">
<delete dir="${build}" />
<delete file="tserver.jar" />
</target>

</project>
If you will check out the build file, you will see that the classpath contains slf4j-api-x.y.z.jar file. Download these files from http://www.slf4j.org/download.html and put two files (slf4j-api-x.y.z.jar and slf4j-simple-x.y.z.jar) from the archive in the /usr/local/lib directory to satisfy the required dependencies.

To complile the file run ant and create two files runClient and runServer to run the server and clients.

$ ant
$ cat runClient
java -cp tserver.jar:/usr/local/lib/libthrift.jar:/usr/local/lib/slf4j-api-1.5.11.jar:/usr/local/lib/slf4j-simple-1.5.11.jar client.TimeClient
$ cat runServer
java -cp tserver.jar:/usr/local/lib/libthrift.jar:/usr/local/lib/slf4j-api-1.5.11.jar:/usr/local/lib/slf4j-simple-1.5.11.jar server.Server


On compiling you will get the tserver.jar file created.

Now run the server and the client

$ ./runServer
Starting server on port 7911 ...

$ ./runClient
Time from server:1270726146716
Got date from server: 2010-4-8 16:59:6
Multiply from server: 3000


Now lets try building a client in php. First we will generate the thrift-code for php and then write the client to interact with the java server.

$ thrift --gen php time.thrift
$ mkdir php # create a directory to store your php client source code.
$ cd php
$ vim PhpClient.php

<?php

//location of thrift php libraries
$GLOBALS['THRIFT_ROOT'] = './lib';

require_once $GLOBALS['THRIFT_ROOT'].'/Thrift.php';
require_once $GLOBALS['THRIFT_ROOT'].'/protocol/TBinaryProtocol.php';
require_once $GLOBALS['THRIFT_ROOT'].'/transport/TSocket.php';
require_once $GLOBALS['THRIFT_ROOT'].'/transport/THttpClient.php';
require_once $GLOBALS['THRIFT_ROOT'].'/transport/TBufferedTransport.php';

error_reporting(E_ALL);
$GEN_DIR = '../gen-php';
require_once $GEN_DIR.'/time/TimeServer.php';
require_once $GEN_DIR.'/time/time_types.php';
error_reporting(E_ALL);

try {
  $socket = new TSocket('localhost', 7911);
  $transport = new TBufferedTransport($socket, 1024, 1024);
  $protocol = new TBinaryProtocol($transport);
  // this client depends on the client class in the gen-php/time/TimeServer.php file
  // class TimeServerClient implements TimeServerIf
  $client = new TimeServerClient($protocol);

  $transport->open();

  $time = $client->time();
  print "time frm server = $time\n";
  $res = $client->multiply(100,5000);
  print "multiply frm server = $res\n";
  $transport->close();

} catch (TException $tx) {
  print 'TException: '.$tx->getMessage()."\n";
}
?>
As you can see, in the code, the thrift library for php is included in the lib directory inside the php directory.
Create the lib directory and copy the required library files from thrift installation directory to the lib directory.

$ mkdir lib
$ cp -r /path/to/thrift/lib/php/src/* lib/


Now try running your php client. Remember to fire up your java server.

$ php -q PhpClient.php

You may get tons of errors "failed opening './lib/packages/time/time_types.php' for inclusion". For this you will need to edit the generated php files. The time_types.php file is in the generated directory "gen-php".

$ vim ../gen-php/time/TimeServer.php

Add the following lines

include_once '../gen-php/time/time_types.php';
//include_once $GLOBALS['THRIFT_ROOT'].'/packages/time/time_types.php';

now "php -q PhpClient.php" works...

Monday, March 22, 2010

Design patterns : Decorator pattern

A decorator is a class which wraps the original class. This allows the user to extend the functionality of certain objects at runtime. The pattern is designed in a way that multiple decorators can be stacked on top of each other. Decorators are used to avoid the rigidity that subclassing provides.

php example
<?php                                                                                                                                                                   
/**                                                                                                                                                                     
 * The smallest cohesive interface we can think of for this type        
 * of Decorator. This is the Component interface.
*/                                                                                                                                                                     
interface HtmlElement                                                   
{ /**                                                                                                * @return string    html code
*/                                                                                                                                                                   
  public function __toString();                                         

  /**
   * @return string    the name of the POST request key for this element,
   *                   aka the "name" attribute.                         
   */                                                                    
  public function getName();                                             
}                                                                        

/**
 * Represents a <input type="text" /> html element.
 * It can be created programmatically and then printed.  
 * This is the only ConcreteComponent.                   
 */                                                      
class InputText implements HtmlElement                   
{                                                        
  protected $_name;                                      

  public function __construct($name)
  {                                 
    $this->_name = $name;           
  }                                 

  public function getName()
  {                        
    return $this->_name;   
  }                        

  public function __toString()
  {                           
    return "<input type=\"text\" id=\"{$this->_name}\" name=\"{$this->_name}\" />\n";
  }                                                                                        
}                                                                                          

/**
 * Very simple base class to share the wrapping code between Decorators.
 * This is the Decorator participant.                                   
 */                                                                     
abstract class HtmlDecorator implements HtmlElement                     
{                                                                       
  protected $_element;                                                  

  public function __construct(HtmlElement $input)
  {                                              
    $this->_element = $input;                    
  }                                              

  /**
   * All operations are delegated by default, not changing anything
   * of the original behavior.                                     
   * ConcreteDecorators will override the methods they are interested in.
   */                                                                    
  public function getName()                                              
  {                                                                      
    return $this->_element->getName();                                   
  }                                                                      

  public function __toString()
  {                           
    return $this->_element->__toString();
  }                                      
}                                        

/**
 * Adds a custom <label> element alongside the <input> one.
 * Example of ConcreteDecorator.                           
 */                                                        
class LabelDecorator extends HtmlDecorator                 
{
  protected $_label;                                       

  public function setLabel($label)
  {                               
    $this->_label = $label;       
  }                               

  public function __toString()
  {                           
    $name = $this->getName(); 
    return "<label for=\"{$name}\">{$this->_label}</label>\n"
      . $this->_element->__toString();                                      
  }                                                                         
}                                                                           

/**
 * Adds a <span> containing an error message after the <input> element.
 * Example of ConcreteDecorator.                                       
 */                                                                    
class ErrorDecorator extends HtmlDecorator                             
{                                                                      
  protected $_error;                                                   

  public function setError($message)
  {                                 
    $this->_error = $message;       
  }                                 

  public function __toString()
  {                           
    return $this->_element->__toString()
      . "<span>{$this->_error}</span>\n";
  }                                                     
}                                                       

$input = new InputText('nickname');
$labelled = new LabelDecorator($input);
$labelled->setLabel('Nick:');          
echo "Using labelDecorator => \n",$labelled, "\n";

$input = new InputText('nickname');
$error = new ErrorDecorator($input);
$error->setError('You must enter a unique nickname');
echo "Using errorDecorator => \n",$error, "\n";   

// how can we obtain a LabelledErrorInputText, which has both the <label>
// and <span> elements?                                                  
$input = new InputText('nickname');                                      
$labelled = new LabelDecorator($input);                                  
$labelled->setLabel('Nick:');                                            
$error = new ErrorDecorator($labelled); // a Decorator wrapping another one
$error->setError('You must enter a unique nickname');                      
echo "Using both labelDecorator & errorDecorator => \n".$error;         
?>                                                                         

Output : 

Using labelDecorator =>
<label for="nickname">Nick:</label>
<input type="text" id="nickname" name="nickname" />

Using errorDecorator =>
<input type="text" id="nickname" name="nickname" />
<span>You must enter a unique nickname</span>

Using both labelDecorator & errorDecorator =>
<label for="nickname">Nick:</label> 
<input type="text" id="nickname" name="nickname" />
<span<You must enter a unique nickname>/span>


Some code in java

interface iComponent                                             
{                                                                
  public void doStuff();                                         
}                                                                

class component implements iComponent
{                                    
  public void doStuff()              
  {                                  
    System.out.println("component does stuff");
  }                                            
}                                              

interface decorator extends iComponent
{                                     
  public void addedBehaviour();       
}                                     

class concreteDecorator implements decorator
{                                           
  iComponent comp;                          
  public concreteDecorator(iComponent comp) 
  {                                         
    super();                                
    this.comp = comp;                       
  }                                         

  public void addedBehaviour()
  {                           
    System.out.println("Added behaviour in decorator");
  }                                                    

  public void doStuff()
  {                    
    comp.doStuff();    
    addedBehaviour();  
  }                    
}                      

class concreteDeco2 implements decorator
{                                       
  iComponent comp;                      
  public concreteDeco2(iComponent comp) 
  {                                     
    super();                            
    this.comp = comp;                   
  }                                     

  public void addedBehaviour()
  {
    System.out.println("Added behaviour in deco no 2");
  }

  public void doStuff()
  {
    comp.doStuff();
    addedBehaviour();
  }

}

public class decoClient
{
  public static void main(String[] args)
  {
    iComponent comp = new component();
    decorator deco = new concreteDecorator(comp);
    deco.doStuff();
    decorator deco2 = new concreteDeco2(comp);
    deco2.doStuff();
  }
}

Output :

component does stuff
Added behaviour in decorator
component does stuff
Added behaviour in deco no 2

Friday, March 05, 2010

Storing trees in databases

A tree is a graph which is connected, uni-directed and acyclic. Lets look at different options of storing such trees in databases.

Parent - Child Model

The most common model for storing hierarchical information is storing the reference of the parent node along with the child node.

so for a tree

EmployeeBosssalary
ANULL1000
BA900
CA950
DC800
EC700
FC600

For this model, the table to be created would be:

create table employee_tree(employee varchar(10) not null primary key, boss varchar(10), salary decimal(10,2) not null);

Some sample operations :
  • Finding the root node : select * from employee_tree where boss is NULL
  • Finding all leaf nodes : select e1.* from employee_tree as e1 left join employee_tree as e2 on e1.employee=e2.boss where e2.employee is null
  • Retrieving a single path : select e1.employee as lev1, e2.employee as lev2, e3.employee as lev3 from employee_tree as e1 left join employee_tree as e2 on e2.boss = e1.employee left join employee_tree as e3 on e3.boss = e2.employee where e1.employee = 'A' and e3.employee='F';

Some problems with this model:
  • Update : if you run "update employee_tree set employee = 'C1' where employee='C'", then all nodes below "C" are left with boss who does notexist. To handle this, you should run a transaction with two queries, one being the above query and another being the query "update employee_tree set boss = 'C1' where employee = 'C'"
  • Insert : if you run a query "Insert into employee_tree (employee, boss) values ('G','H'),('H','G')" you get two employees 'G' & 'H' who are both employees and bosses of each other.
  • Insert : Another problem with insert is "Insert into employee_tree (employee, boss) values ('M','M')". Now 'M' is the boss of 'M'.
  • Delete : Run "Delete from employee_tree where emp = 'C'". Again we create a situation where 'D','E','F' are left with a boss who does not exist. So in effect, deletion would require the tree to be traversed.
  • Descendants : It is difficult to get the number of descendents for a given node in a single query. You will have to write some script and un some recursive function to get that number

Fixing this model: Following checks should be in place to fix this model.
  • An employee cannot be his own boss : Check if ( boss != employee ) or (boss = 0 and employee = 0)
  • On deletion use cascade to remove the employees to that boss
  • To prevent cyclic relations : add unique key (employee, boss)
  • Check for validity of tree (edges = nodes - 1) : count(*) from employee_tree - 1 = count(boss) from employee_tree where boss is not null
  • Check for only single root : select count(*) from employee_tree where boss_id is null = 1

Path Enumeration model

create table employee(emp_id char(1) not null primary key, emp_name varchar(10), emp_path varchar(255) not null);
emp_idemp_nameemp_path
AA NameA
BB NameAB
CC NameAC
DD NameACD
EE NameACE
FF NameACF
The sample operations are easy here
  • Finding root node : select * from employee where length(emp_path)=1;
  • Finding all leaf nodes : This is going to be difficult, You will have to write a script to extract this info
  • Prevent cyclic relations : check whether after removing the node from the path string, the path is reduced by only 1 node. Query : CHECK(NOT EXISTS(select * from employee as e1, employee as e2 where length(replace(e1.emp_path,e2.emp_id,'')) < (length(e1.emp_path)-length(e2.emp_id)) ));
  • No path can be longer than the total no of nodes in the tree : CHECK( (select max(length(e1.emp_path)) from employee as e1) <= (select coun t(e2.emp_id) * length(e2.emp_id) from employee as e2) )
  • Depth of the tree is the path divided by the length of emp_id string : CHAR_LENGTH(emp_path) / CHAR_LENGTH(emp_id); If emp_ids are not fixed length then the depth is : CHAR_LENGTH(emp_path) - CHAR_LENGTH(REPLACE(emp_path,'/','')) + 1 [here / is the separator that is path is written as 'A/B/C'. If you use any other separator, you need to change it in the function as well]
  • To find all subtrees for a parent : the immediate solution is "Select * from employee where emp_path like concat('%',<Parent_emp_id>,'%')". But this query does not use indexes. Another way of doing this is "select * from employee where emp_path like concat((select emp_path from employee where emp_id='<Parent_emp_id>'),'%');"
  • To find the immediate subchildren of a parent : "select * from employee where emp_path like concat((select emp_path from employee where emp_id='<Parent_emp_id>'),'_');"
  • To search for superiors : "create table sequence(seq int not null); insert into sequence values (1),(2),(3),(4),(5); select substring(e1.emp_path from (seq * char_length(e1.emp_id)) for char_length(e1.emp_id)) as emp_id from employee e1, sequence s1 where e1.emp_id = '<emp_id_to_search_for>' and s1.seq <= char_length(e1.emp_path)/char_length(e1.emp_id);"
  • To find the relationships among superiors : "select e2.* from employee e1, employee e2 where e1.emp_id = '<emp_id_to_search_for>' and POSITION(e2.emp_path in e1.emp_path) = 1;"
  • To delete a subtree : "DELETE from employee where emp_path like concat(select emp_path from employee where emp_id='<Dead_node_emp_id>','%')" We may need to write the two queries separately;
  • To delete a node : "Delete from employee where emp_id='<emp_id_of_dead_node>'" And "Update employee set emp_path = replace(emp_path,'<emp_id_of_dead_node>','')" Both queries should be in a single transaction.
  • Inserting a node : "select emp_path from employee where emp_id = '<emp_id_of_boss>'; insert into employee values ('<new_emp_id>','<new_emp_name>',concat('<selected_emp_boss_path>','<new_emp_id>'))"

A derivative of the path enumeration model is the edge enumeration model. In Edge enumeration model the path consists of a set of integers that make the path from the root to the node - from left to right.

For example :
Employee nameEdge path
A1.
B1.1.
C1.2.
D1.2.1
E1.2.2
F1.2.3
The benefit of the edge enumeration model over the path enumeration model is that you do not have to worry about long strings. The numbers give an implied ordering to siblings that have meaning.

Nested set model


Here each node is assigned a beginning and an ending node hierarchy number based on the total amount of data in the hierarchical tree.

An example table could be :

create table emp(emp_id int not null auto_increment primary key, emp_name varchar(10), lft int not null, rgt int not null);
Emp idEmp NameLftRgt
1A112
2B23
3C411
4D56
5E78
6F910
Operations in this model:
  • Finding the root node : "select * from emp where lft = 1"
  • Finding leaf nodes : "select * from emp where lft = rgt - 1"
  • Finding subtree : select node.* from emp as node, emp as parent where node.lft > parent.lft and node.lft < parent.rgt and parent.emp_id='&l t;parent_employee_id>';"
  • Retrieving a single path : "select parent.* from emp as node, emp as parent where node.lft > parent.lft and node.lft < parent.rgt and node. emp_id='<leaf_node_id>' order by parent.lft;"
  • Finding depth of nodes : "select node.emp_name, (COUNT(parent.emp_name)-1) as depth from emp as node, emp as parent where node.lft BETWEEN parent.lft and parent.rgt group by node.emp_name order by node.lft;"
  • Add a single node as child of node with no existing children : If you want to insert a node 'G' below 'B', then the new node 'G' would have left and right values '3' and '4' and all nodes after it (in sequence) would have to increase their left and right values by 2. The procedure
    for it would be
    lock table emp write;
    select @myleft := lft from emp where emp_name='<add_below_this_node>';
    update emp set rgt = rgt+2 where rgt > @myleft;
    update emp set lft = lft+2 where lft > @myleft;
    insert into emp values ('','G',&myleft+1,@myleft+2);
    unlock tables;
    
  • As a single node after a node(not as a new child) : modify the earlier procedure a little.
    lock table emp write;
    select @myright := rgt from emp where emp_name='<add_after_this_node>';
    update emp set rgt = rgt+2 where rgt > @myright;
    update emp set lft = lft+2 where lft > @myright;
    insert into emp values ('','G',&myright+1,@myright+2);
    unlock tables;
    
  • Delete a node and its children : Deletion is just opposite to a adding. After deletion, its width has to be deleted from all nodes to the right.
    lock table emp write;
    select @myleft := lft, @myright := rgt, @mywidth := rgt - lft + 1 from emp where emp_name='<node_to_be_deleted>';
    delete from emp where lft between @myleft and @myright;
    update emp set rgt = rgt - @mywidth where rgt > @myright;
    update emp set lft = lft - @mywidth where lft > @myright;
    unlock tables;
    
  • Delete only the parent node: In this case the child nodes will have to be moved up to the level of the parent.
    lock table emp write;
    select @myleft := lft, @myright := rgt, @mywidth := rgt - lft + 1 from emp where emp_name='<parent_to_be_deleted>';
    delete from emp where lft = @myleft;
    update emp set rgt = rgt - 1, lft = lft - 1 where lft between @myleft and @myright;
    update emp set rgt = rgt - 2 where rgt > @myright;
    update emp set lft = lft - 2 where lft > @myleft;
    unlock tables;
    
Hybrid model

A parent child with nested set model would server the purpose much better. (node, parent, left, right). But with hybrid models, inserts would be more expensive as compared to selects. So it is important to evaluate the pros and cons and figure out what would be best for the purpose tha t your application serves.

Nested intervals model.

This model is similar to the nested set model with the use of rational numbers (a/b) instead of numbers. So in our above tree the left and right values would change.
Emp idEmp NameLftRgt
1A0/1111/11
2B1/112/11
3C3/1110/11
4D4/115/11
5E6/117/11
6F8/119/11

This is a bit complex to implement, but plays well with all the queries.

Proprietary solutions

Oracle, DB2 and Microsoft SQL Server support heirarchial data. In opensource Postgresql 8.4 supports the addition and querying of heirarchial data basically by using a "CONNECT BY" clause. It would be better if their official documentation is referred to for info regarding the syntax for implementing heirarchial data in relational databases.

Sunday, February 28, 2010

Options available for heating water

The simplest and easiest way is to get a big utensil and fill it up with water and heat it on the stove. Remember to cover it up, and it gets hot faster.

Another option that we used when we were living as tenants was an electric rod. It costs between 200 to 500 INR and depending upon the wattage heats up water fast - a bucket gets heated in say 15 minutes if you are using an element of around 2KW. It is cheap and electric - so wont work if you have power cuts. But it saves the trouble of lighting up your gas and placing an utencil above it. The bigger the bucket the more water you can heat. Be careful, if the element gets sorted, you might get a shock or even trip your main supply.

Third option is getting an electric water geaser. It has its own pros and cons. Electric water geasers cost from around 4000 INR and move up. All of them have a plastic body, a heating element, a tank, a thermostat and some electronic stuff. The difference between a cheap one and an expensive one is basically the quality of these things. A cheap one may have a steel tank, whereas an expensive one may have a copper tank, and some even have tanks lined with glass - to prevent damage to the tank due to hard water. The life of an element is minimum 3 months, after which depending on the quality of water that you get, it will get sorted. Once it gets sorted, you will experience an electric shock whenever you try getting water from a geaser which is switched on. Imagine getting a "shocking" shower. The worst that can happen is when the tank leaks, it will sort the thermostat, maybe the electronics and you will again get a "shocking" shower - but this time the water might be either very cold or very hot. The thermostat costs around 300 INR, the element costs around 500 INR, the tank costs around 1000 INR. Other logistical issues with a storage type of water heater is the pressure. In case you are on the ground floor and the water comes from a tank at the 10th floor, the pressure will be too much for the tank to handle (dont worry, it wont explode, it will simply leak). To avoid it, you will need to get a pressure valve.

Another option in the electrical segment is the "non-storage" type of water heater. It has an element and heats water on the fly. It is cheaper, cause it does not have a tank but it has not been very successful mainly because the water does not get very hot - just warm. And, again if the element gets sorted, be ready to experience a "shocking shower".

If we move out of the electrical option, there are two other options available, the solar option and the gas option. Lets talk about the gas option.

No this is not the "heat in pan" option. There are geasers available in market which run on gas and heat water. Basically a gas geaser has two inputs (water & gas) and an output (hot water). It does not store water. Water runs through pipes among a burning stove and heats up. The cost of a gas geaser is around 2500 INR with installation - you need to have your own gas supply ofcourse. Again this thing does not have a storage, so water is heated on the fly. Gas geaser is supposed to be a lot cheaper (running cost) as compared to an electric geaser - mainly because gas is cheaper than electricity and the effeciency of gas is better than electricity while heating. Here it says that yearly savings are around 3500/- INR. The bad thing about the gas geaser is that it burns up oxygen wherever it is installed. So if you install it in a bathroom without any ventilation, you might experience dizziness due to low oxygen. This geaser has to be installed near a open window so that it gets all the air it can burn. Installation and usage in a non-ventilated space may cause Carbon Monoxide (CO) poisoning (if there is not enough oxygen to burn CO is produced). So be careful while using it. The benefit as compared to electric water heater is the cheaper running cost and the possibility of not getting an electric shock.

And the last one is the solar water heater. Unless you are not living in an appartment and have your own private sunlight from morning till night, it is not worth exploring. Solar water heaters are a lot expensive but environment friendly and very safe.

Wednesday, February 24, 2010

Design Patterns : Composite Design Pattern

A composite design pattern builds complex objects out of simple objects and itself like a tree structure. Its goal is managing a hierarchy of objects where both leaf objects and composition of other objects conform to a common interface.

The client sends a message to the head component. The component declares the interface that various parts of the graph should respect. A leaf is a concrete class that has no children. A composite is a concrete class that composes other components.

PHP Code :

/**
 * Component interface.
 * The Client depends only on this abstraction, whatever graph is built using
 * the specializations.
 */
interface HtmlElement
{
  /**
   * @return string   representation
   */
  public function __toString();
}

/**
 * Leaf sample implementation.
 * Represents an <h1> element.
 */
class H1 implements HtmlElement
{
  private $_text;

  public function __construct($text)
  {
    $this->_text = $text;
  }

  public function __toString()
  {
    return "<h1>{$this->_text}</h1>";
  }
}

/**
 * Leaf sample implementation.
 * Represents a <p> element.
 */
class P implements HtmlElement
{
  private $_text;

  public function __construct($text)
  {
    $this->_text = $text;
  }

  public function __toString()
  {
    return "<p>{$this->_text}</p>";
  }
}

/**
 * A Composite implementation, which accepts as children generic Components.
 * These children may be H1, P or even other Divs.
 */
class Div implements HtmlElement
{
  private $_children = array();

  public function addChild(HtmlElement $element)
  {
    $this->_children[] = $element;
  }

  public function __toString()
  {
    $html = "<div>\n";
    foreach ($this->_children as $child) {
      $childRepresentation = (string) $child;
      $childRepresentation = str_replace("\n", "\n    ", $childRepresentation);
      $html .= '    ' . $childRepresentation . "\n";
    }
    $html .= "</div>";
    return $html;
  }
}

// Client code
$div = new Div();
$div->addChild(new H1('Title'));
$div->addChild(new P('Lorem ipsum...'));
$sub = new Div();
$sub->addChild(new P('Dolor sit amet...'));
$div->addChild($sub);
echo $div, "\n";


Output

<div>
  <h1>Title</h1>
  <p>Lorem ipsum...</p>
  <div>
    <p>Dolor sit amet...</p>
  </div>
</div>

Java Code : 

import java.util.List;
import java.util.ArrayList;

/** "Component" */
interface Graphic {

  //Prints the graphic.
  public void print();
}

/** "Composite" */
class CompositeGraphic implements Graphic {

  //Collection of child graphics.
  private List mChildGraphics = new ArrayList();

  //Prints the graphic.
  public void print() {
    for (Graphic graphic : mChildGraphics) {
      graphic.print();
    }
  }

  //Adds the graphic to the composition.
  public void add(Graphic graphic) {
    mChildGraphics.add(graphic);
  }

  //Removes the graphic from the composition.
  public void remove(Graphic graphic) {
    mChildGraphics.remove(graphic);
  }
}

/** "Leaf" */
class Ellipse implements Graphic {

  String myname = "Ellipse";

  public Ellipse(int i){
    this.myname = myname + ":"+i;
  }

  //Prints the graphic.
  public void print() {
    System.out.println(this.myname);
  }
}

/** Client */
public class Program {

  public static void main(String[] args) {
    //Initialize four ellipses
    Ellipse ellipse1 = new Ellipse();
    Ellipse ellipse2 = new Ellipse();
    Ellipse ellipse3 = new Ellipse();
    Ellipse ellipse4 = new Ellipse();

    //Initialize three composite graphics
    CompositeGraphic graphic = new CompositeGraphic();
    CompositeGraphic graphic1 = new CompositeGraphic();
    CompositeGraphic graphic2 = new CompositeGraphic();

    //Composes the graphics
    graphic1.add(ellipse1);
    graphic1.add(ellipse2);
    graphic1.add(ellipse3);

    graphic2.add(ellipse4);

    graphic.add(graphic1);
    graphic.add(graphic2);

    //Prints the complete graphic (four times the string "Ellipse").
    graphic.print();
  }
}

OUTPUT:

Ellipse:1
Ellipse:2
Ellipse:3
Ellipse:4

Wednesday, February 10, 2010

Design patterns : Bridge Design Pattern

Bridge pattern decouples the abstraction from its implementation so that both can vary independently. It is quite similar to the adapter pattern. An adapter pattern makes two unrelated, existing classes work together, when the two participants were not thought to be aware of each other during design. A bridge pattern separates concerns and is chosen at the design level before the creation of participating classes.

There is an abstraction that the client sees. There is an implementor which provides the interface for actual implementation. A refined abstraction which provides extension to the abstraction's functionalities. And a ConcreteImplementor which is an implementation of the implementor.

PHP Code :

abstract class BridgeBook
{
  private $bbAuthor;
  private $bbTitle;
  private $bbImp;
  function __construct($author_in, $title_in, $choice_in)
  {
    $this->bbAuthor = $author_in;
    $this->bbTitle  = $title_in;
    if ('STARS' == $choice_in)
    {
      $this->bbImp = new BridgeBookStarsImp();
    } else
    {
      $this->bbImp = new BridgeBookCapsImp();
    }
  }
  function showAuthor()
  {
    return $this->bbImp->showAuthor($this->bbAuthor);
  }
  function showTitle()
  {
    return $this->bbImp->showTitle($this->bbTitle);
  }
}

class BridgeBookAuthorTitle extends BridgeBook
{
  function showAuthorTitle()
  {
    return $this->showAuthor() . "'s " . $this->showTitle();
  }
}

class BridgeBookTitleAuthor extends BridgeBook
{
  function showTitleAuthor()
  {
    return $this->showTitle() . ' by ' . $this->showAuthor();
  }
}

abstract class BridgeBookImp
{
  abstract function showAuthor($author);
  abstract function showTitle($title);
}

class BridgeBookCapsImp extends BridgeBookImp
{
  function showAuthor($author_in)
  {
    return strtoupper($author_in);
  }
  function showTitle($title_in)
  {
    return strtoupper($title_in);
  }
}

class BridgeBookStarsImp extends BridgeBookImp
{
  function showAuthor($author_in)
  {
    return Str_replace(" ","*",$author_in);
  }
  function showTitle($title_in)
  {
    return Str_replace(" ","*",$title_in);
  }
}

echo('BEGIN'."\n");

echo('test 1 - author title with caps');
$book = new BridgeBookAuthorTitle('Larry Truett','PHP for Cats','CAPS');
echo($book->showAuthorTitle());
echo("\n");

echo('test 2 - author title with stars');
$book = new BridgeBookAuthorTitle('Larry Truett','PHP for Cats','STARS');
echo($book->showAuthorTitle());
echo("\n");

echo('test 3 - title author with caps');
$book = new BridgeBookTitleAuthor('Larry Truett','PHP for Cats','CAPS');
echo($book->showTitleAuthor());
echo("\n");

echo('test 4 - title author with stars');
$book = new BridgeBookTitleAuthor('Larry Truett','PHP for Cats','STARS');
echo($book->showTitleAuthor());
echo("\n");

echo('END'."\n");

Output : 
BEGIN
test 1 - author title with capsLARRY TRUETT's PHP FOR CATS
test 2 - author title with starsLarry*Truett's PHP*for*Cats
test 3 - title author with capsPHP FOR CATS by LARRY TRUETT
test 4 - title author with starsPHP*for*Cats by Larry*Truett
END



Java Code :

/** "Implementor" */
interface DrawingAPI 
{
  public void drawCircle(double x, double y, double radius);
}

/** "ConcreteImplementor" 1/2 */
class DrawingAPI1 implements DrawingAPI 
{
  public void drawCircle(double x, double y, double radius) 
  {
    System.out.printf("API1.circle at %f:%f radius %f\n", x, y, radius);
  }
}

/** "ConcreteImplementor" 2/2 */
class DrawingAPI2 implements DrawingAPI 
{
  public void drawCircle(double x, double y, double radius) 
  { 
    System.out.printf("API2.circle at %f:%f radius %f\n", x, y, radius);
  }
}

/** "Abstraction" */
interface Shape 
{
  public void draw();                             // low-level
  public void resizeByPercentage(double pct);     // high-level
}

/** "Refined Abstraction" */
class CircleShape implements Shape 
{
  private double x, y, radius;
  private DrawingAPI drawingAPI;
  public CircleShape(double x, double y, double radius, DrawingAPI drawingAPI) 
  {
    this.x = x;  
    this.y = y;  
    this.radius = radius; 
    this.drawingAPI = drawingAPI;
  }

  // low-level i.e. Implementation specific
  public void draw() 
  {
    drawingAPI.drawCircle(x, y, radius);
  }   
  // high-level i.e. Abstraction specific
  public void resizeByPercentage(double pct) 
  {
    radius *= pct;
  }
}

/** "Client" */
public class Bridge
{
  public static void main(String[] args) 
  {
    Shape[] shapes = new Shape[2];
    shapes[0] = new CircleShape(1, 2, 3, new DrawingAPI1());
    shapes[1] = new CircleShape(5, 7, 11, new DrawingAPI2());

    for (Shape shape : shapes) 
    {
      shape.resizeByPercentage(2.5);
      shape.draw();
    }
  }
}

Output :

API1.circle at 1.000000:2.000000 radius 7.500000
API2.circle at 5.000000:7.000000 radius 27.500000

Tuesday, February 09, 2010

Design patterns : Adapter Design Pattern

Adapter design pattern converts the interface of a class into another interface that the client expects. It lets the classes work together that otherwise could not because of incompatible interfaces. It wraps the existing class in a compatible interface acceptible to the the client.

The actors here are the client - which makes use of an object which implements the target interface, the target is the point of extension of the client module, adaptee - object of different module or library and the adapter is an implementation of the target which forwards real work to the adaptee and also hides him from the client.

PHP Code :

class SimpleBook
{
  private $author;
  private $title;
  function __construct($author_in, $title_in)
  {
    $this->author = $author_in;
    $this->title  = $title_in;
  }
  function getAuthor()
  {
    return $this->author;
  }
  function getTitle()
  {
    return $this->title;
  }
}

class BookAdapter
{
  private $book;
  function __construct(SimpleBook $book_in)
  {
    $this->book = $book_in;
  }
  function getAuthorAndTitle()
  {
    return $this->book->getTitle().' by '.$this->book->getAuthor();
  }
}

// client

echo "BEGIN\n";

$book = new SimpleBook("PHP Author", "PHP Book on Design patterns");
$bookAdapter = new BookAdapter($book);
echo "Author and Title: ".$bookAdapter->getAuthorAndTitle()."\n";

echo "END\n";

Output:

BEGIN
Author and Title: PHP Book on Design patterns by PHP Author
END

JAVA Code:

class LegacyLine
{
  public void draw(int x1, int y1, int x2, int y2)
  {
    System.out.println("line from (" + x1 + ',' + y1 + ") to (" + x2 + ','  + y2 + ')');
  }
}

class LegacyRectangle
{
  public void draw(int x, int y, int w, int h)
  {
    System.out.println("rectangle at (" + x + ',' + y + ") with width " + w  + " and height " + h);
  }
}

interface Shape
{
  void draw(int x1, int y1, int x2, int y2);
}

class Line implements Shape
{
  private LegacyLine adaptee = new LegacyLine();
  public void draw(int x1, int y1, int x2, int y2)
  {
    adaptee.draw(x1, y1, x2, y2);
  }
}

class Rectangle implements Shape
{
  private LegacyRectangle adaptee = new LegacyRectangle();
  public void draw(int x1, int y1, int x2, int y2)
  {
    adaptee.draw(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x2 - x1),   Math.abs(y2 - y1));
  }
}

public class AdapterDemo
{
  public static void main(String[] args)
  {
    Shape[] shapes = 
    {
      new Line(), new Rectangle()
    };
    // A begin and end point from a graphical editor
    int x1 = 10, y1 = 20;
    int x2 = 30, y2 = 60;
    for (int i = 0; i < shapes.length; ++i)
      shapes[i].draw(x1, y1, x2, y2);
  }
}

Output : 

line from (10,20) to (30,60)
rectangle at (10,20) with width 20 and height 40

Design Patterns : Prototype pattern

The prototype pattern specifies the kind of objects to create using a prototypical instance, and creates new objects by copying the prototype. A clone method is available in the class which can be used to create new objects of the same kind.

The pattern consists of a prototype - an interface of the cloneable classes. A ConcretePrototype implements the clone operations and a client actually clones the prototype instance to use the clones as new objects.

Simple examples

PHP
abstract class BookPrototype
{
  protected $title;
  protected $topic;
  abstract function __clone();
  function getTitle()
  {
    return $this->title;
  }
  function setTitle($titleIn)
  {
    $this->title = $titleIn;
  }
  function getTopic()
  {
    return $this->topic;
  }
}

class PHPBookPrototype extends BookPrototype
{
  function __construct()
  {
    $this->topic = 'PHP';
  }
  function __clone()
  {  }
}

class SQLBookPrototype extends BookPrototype
{
  function __construct()
  {
    $this->topic = 'SQL';
  }
  function __clone()
  {  }
}

echo("BEGIN \n");

$phpProto = new PHPBookPrototype();
$sqlProto = new SQLBookPrototype();

$book1 = clone $sqlProto;
$book1->setTitle('SQL Book prototype');
echo('Book 1 topic: '.$book1->getTopic()."\n");
echo('Book 1 title: '.$book1->getTitle()."\n");

$book2 = clone $phpProto;
$book2->setTitle('PHP Book prototype');
echo('Book 2 topic: '.$book2->getTopic()."\n");
echo('Book 2 title: '.$book2->getTitle()."\n");

$book3 = clone $sqlProto;
$book3->setTitle('SQL Book prototype II');
echo('Book 3 topic: '.$book3->getTopic()."\n");
echo('Book 3 title: '.$book3->getTitle()."\n");

echo("END\n");

Output:

BEGIN 
Book 1 topic: SQL
Book 1 title: SQL Book prototype
Book 2 topic: PHP
Book 2 title: PHP Book prototype
Book 3 topic: SQL
Book 3 title: SQL Book prototype II
END

Java :

public class proto 
{
  interface Xyz 
  {
    Xyz cloan();
  }

  static class Tom implements Xyz 
  {
    public Xyz cloan()    
    {
      return new Tom();
    }
    public String toString() 
    {
      return "tom prototype";
    }
  }

  static class Dick implements Xyz 
  {
    public Xyz    cloan()    
    {
      return new Dick();
    }
    public String toString() 
    {
      return "dick prototype";
    }
  }

  static class Harry implements Xyz 
  {
    public Xyz    cloan()    
    {
      return new Harry();
    }
    public String toString() 
    {
      return "harry prototype";
    }
  }

  static class Factory 
  {
    private static java.util.Map prototypes = new java.util.HashMap();
    static 
    {
      prototypes.put( "tom",   new Tom() );
      prototypes.put( "dick",  new Dick() );
      prototypes.put( "harry", new Harry() );
    }
    public static Xyz makeObject( String s ) 
    {
      return ((Xyz)prototypes.get(s)).cloan();
    }
  }

  public static void main( String[] args ) 
  {
    for (int i=0; i < args.length; i++) 
    {
      System.out.println( Factory.makeObject( args[i] ) + "  " );
    }
  }
}

Output : 
$ java proto tom dick harry harry tomtom prototype  
dick prototype  
harry prototype  
harry prototype  
tom prototype 

Monday, February 08, 2010

Design patterns : Factory Method

Factory method defines an interface for creating an object, but lets the subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclasses.

Factory method makes the design more customizable and only a little more complicated. Other design patterns require new classes whereas factory method requires only a new operation.

Factory method is quite similar to the Abstract Factory. In fact every relevant method of Abstract Factory is a Factory Method. Factory methods could be moved out of their classes in subsequent refactoring and evolve in an external Abstract Factory.

The participating actors are the "Product" - the abstraction of the created object, a "concrete product" - an implementation of the product. "Creator" is the base class which declares a default Factory Method and "ConcreteCreator" is a subclass of the creator which overrides the Factory Method to return a Concrete Product.

Lets check some code

PHP : lets check some code similar to those we wrote for Abstract Factory
abstract class AbstractFactoryMethod
{
  abstract function makeBook($param);
}

class OReillyFactoryMethod extends AbstractFactoryMethod
{
  private $context = "OReilly";
  function makeBook($param)
  {
    $book = NULL;
    switch($param)
    {
      case "PHP":
        $book = new OReillyPHPBook;
      break;
      case "MySQL":
        $book = new OReillyMySQLBook;
      break;
      default:
      $book = new OReillyPHPBook;
      break;
    }
    return $book;
  }
}

class SAMSFactoryMethod extends AbstractFactoryMethod
{
  private $context = "SAMS";
  function makeBook($param)
  {
    $book = NULL;
    switch($param)
    {
      case "PHP":
        $book = new SamsPHPBook;
      break;
      case "MySQL":
        $book = new SamsMySQLBook;
      break;
      default:
      $book = new SamsMySQLBook;
      break;
    }
    return $book;
  }
}

abstract class AbstractBook
{
  abstract function getAuthor();
  abstract function getTitle();
}

class OReillyPHPBook extends AbstractBook
{
  private $author;
  private $title;
  function __construct()
  {
    $this->author = "Author - OReilly php";
    $this->title = "Title - OReilly php";
  }

  function getAuthor() {return $this->author;}
  function getTitle() {return $this->title;}
}

class SamsPHPBook extends AbstractBook
{
  private $author;
  private $title;
  function __construct()
  {
    $this->author = "Author - SAMS php";
    $this->title = "Title - SAMS php";
  }

  function getAuthor() {return $this->author;}
  function getTitle() {return $this->title;}
}

class OReillyMySQLBook extends AbstractBook
{
  private $author;
  private $title;
  function __construct()
  {
    $this->author = "Author - OReilly MySQL";
    $this->title = "Title - OReilly MySQL";
  }

  function getAuthor() {return $this->author;}
  function getTitle() {return $this->title;}
}

class SamsMySQLBook extends AbstractBook
{
  private $author;
  private $title;
  function __construct()
  {
    $this->author = "Author - SAMS MySQL";
    $this->title = "Title - SAMS MySQL";
  }

  function getAuthor() {return $this->author;}
  function getTitle() {return $this->title;}
}

function testFactoryMethod($factoryMethodInstance)
{
  $phpBook = $factoryMethodInstance->makeBook("PHP");
  echo "php author : ".$phpBook->getAuthor()."\n";
  echo "php title : ".$phpBook->getTitle()."\n";

  $mysqlBook = $factoryMethodInstance->makeBook("MySQL");
  echo "mysql author : ".$mysqlBook->getAuthor()."\n";
  echo "mysql title : ".$mysqlBook->getTitle()."\n";
}

echo("Begin\n");
echo("Testing OReillyFactoryMethod\n");
$bookMethodInstance = new OReillyFactoryMethod;
testFactoryMethod($bookMethodInstance);
echo("----\n");

echo("Testing SamsFactoryMethod\n");
$bookMethodInstance = new SamsFactoryMethod;
testFactoryMethod($bookMethodInstance);
echo("----\n");

Output : 

Begin
Testing OReillyFactoryMethod
php author : Author - OReilly php
php title : Title - OReilly php
mysql author : Author - OReilly MySQL
mysql title : Title - OReilly MySQL
----
Testing SamsFactoryMethod
php author : Author - SAMS php
php title : Title - SAMS php
mysql author : Author - SAMS MySQL
mysql title : Title - SAMS MySQL
----

And some example in java

abstract class Pizza 
{
  public abstract int getPrice(); // count the cents
}

class HamAndMushroomPizza extends Pizza 
{
  public int getPrice() 
  {
    return 850;
  }
}

class DeluxePizza extends Pizza 
{
  public int getPrice() 
  {
    return 1050;
  }
}

class HawaiianPizza extends Pizza 
{
  public int getPrice() 
  {
    return 1150;
  }
}

class PizzaFactory 
{
  public enum PizzaType 
  {
    HamMushroom,
      Deluxe,
      Hawaiian
  }

  public static Pizza createPizza(PizzaType pizzaType) 
  {
    switch (pizzaType) 
    {
      case HamMushroom:
        return new HamAndMushroomPizza();
      case Deluxe:
        return new DeluxePizza();
      case Hawaiian:
        return new HawaiianPizza();
    }
    throw new IllegalArgumentException("The pizza type " + pizzaType + " is not recognized.");
  }
}

class myPizza
{
  // Create all available pizzas and print their prices
  public static void main (String args[]) 
  {
    for (PizzaFactory.PizzaType pizzaType : PizzaFactory.PizzaType.values()) 
    {
      System.out.println("Price of " + pizzaType + " is " + PizzaFactory.createPizza(pizzaType).getPrice());
    }
  }
}

Output : 

$ java myPizza 
 Price of HamMushroom is 850
 Price of Deluxe is 1050
 Price of Hawaiian is 1150