Tag Archives: PHP

Multi Tier PHP Application Using RabbitMQ, Web & Worker Architecture

Large Web application needs to have some strategy to ensure web run smoothly. It is also intended to avoid Server down on busy hours.

Imagine thousand to million hits your Server simultaneously. Application could be down even with great hardware specs.
In Hardware point of view, you can do Load Balancing, Traffic Manager, Scale out by adding more Virtual Machine or Scale in by getting higher specs i.e CPU, Memory, HD.
The infrastructure setup is even easier using popular Cloud Portal available widely in market i.e Ms Windows Azure, Amazon Web Service, Google Cloud Platform.
You don’t need to have physical servers on your room. Cloud Portal has menu to create VMs and there are several CPU, Memory, Storage specs options. More high the specs then more costly.
Also you can do Load balancing, Auto/Manual Scaling, Traffic Manager with just some clicks on the Portal.

However considering only H/W and infrastructure sometimes is not enough.
You don’t want to be forced urgently to add more VM or increase H/W specs just because actually you are not managing your application or software properly.

Modern enterprise application use Multi Tier architecture. They use Web and Worker tier for handling users request. On back end side there are database and storage tier.
Web tier contains user interface i.e html body, event handler, etc. Worker is a background process that continuously run and usually used to process jobs which require more computational resources asynchronously .
The main purpose to have web & worker tier is to avoid requests burden application too busy and further more causing your server not responding.

Lets say we have an incident example. There is a web app which has reporting feature sent to user in PDF format. Many clients request for reports simultaneously and those requests are directly processed by database server on same time.
Also after data is retrieved, the Web tier creating many PDF based on requests and send them to clients by email.
Slowness will occur and thus Server either web tier or database will not responding. Not to mention if web tier and database is in one VM only.
You need to stop requests by killing them or just restart the server.

This case is a good example for explaining the need of Worker. So Web tier will sent user request by writing a message to Message Queue instead of sent requests directly to back end or database tier.
Message Queue is just text stored in a Message broker and it has FIFO (First In First Out) for write & read those messages. In this scenario, Web Tier write a request as message to Message Queue
Worker instance that run continuously on background reads client request or message from Message Queue and creating PDF report. The PDF report creation will be sequential based on FIFO of message queue.
So only one report processed in a time for one Worker instance. Lets say you want more report generated in time then you can generate another Worker instance. So you have two or more Workers.
You can manage how many workers you can have based on Server performance.

After Report is generated either that Worker which auto send the report or you may create another Worker to do it.
So first Worker that generate report will write a message to Queue when report is done. Second Worker read a message and send the report.

Below is the schema of multi tier application with Web & Worker Tier.

It is a common scenario and also as a tutorial example in internet since it is understandable with ease.

However this blog post source code is not presenting above schema.
This time we assume for having a Photo Web App and it has more than thousands hits every day like Instagram. This example will retrieve list of photos of followed persons / owner.
Since the Web app hits is quite heavy then we need some strategy using multi tier application.

Basic method to retrieve an image is to download it from database via Web tier and show it to browser. We won’t do that way. We will use Worker to retrieve photos from DB and store them to file storage.
Web tier will show those photos to client browser. The communication between Web & Worker tier use Message queue i.e RabbitMQ.

Please look the schema below:

The difference for this case is the Message Queue has ‘reply-to’ feature. So every request will be replied through Message Queue to ensure Web tier (client) get response immediately after photos are generated.

Many Message Queue available on internet but I use RabbitMQ because of easiness to install and easy to code also.
If you have not familiar yet with RabbitMQ then I suggest you to go to this Url: https://www.rabbitmq.com/getstarted.html and install it to your PC/laptop/dev server.
There is also nice step by step tutorials so you can go through it.
Continue reading

Adapter Pattern OO Design PHP Example

Quoting from Url http://www.oodesign.com/adapter-pattern.html
“The adapter pattern is adapting between classes and objects.
Like any adapter in the real world it is used to be an interface, a bridge between two objects.
In real world we have adapters for power supplies, adapters for camera memory cards, and so on. Probably everyone have seen some adapters for memory cards. If you can not plug in the camera memory in your laptop you can use and adapter.
You plug the camera memory in the adapter and the adapter in to laptop slot. That’s it, it’s really simple.”

It is more clear to understand with example.
PHP Examples

  1. Example 1
    class clsSong {
    	private $title;
    	private $genre
    	function __construct($title, $genre) {
    		$this->title = $title;
    		$this->genre = $genre;		
    	}
    	
    	function getTitle() {
    		return $this->title;
    	}
    	
    	function getGenre() {
    		return $this->genre;
    	}
    }
    
    class clsSong_Adapter {
    	private $objSong;
    	function __construct(clsSong $objSong) {
    		$this->objSong = $objSong;			
    	}
    	
    	function getTitleGenre() {
    		return $this->objSong->getTitle()."/".$this->objSong->getGenre();
    	}
    }
    
    //implementation 
    $objSong = new clsSong("Nothing Else Matter", "Heavy Metal");
    echo $objSong->getTitle()."/".$objSong->getGenre();
    echo "<br>";
    
    $objSngAdapt = new clsSong_Adapter($objSong);
    echo $objSngAdapt->getTitleGenre();
    
    

    Continue reading

DB2 Export Data To CSV With PHP Interface

Reporting with large number of records could be cumbersome if you view it on web page and download the data to CSV or Excel format.
Especially if you are dealing with hundred thousand or millions records.

DB2 has feature for export data or download records directly to external storage i.e your local hard disk.
The way is to specify the data to be exported by supplying an SQL SELECT statement and then use db2 export to download directly to CSV format.

The DB2 syntaxt for this download is db2 export to <filepath/filename> of del <SQL Select statement>.
More complete explanation please go to IBM url https://www.ibm.com/support/knowledgecenter/en/SSEPGG_11.1.0/com.ibm.db2.luw.admin.cmd.doc/doc/r0008303.html

This blog post will explain how to use DB2 export with PHP.
The PHP page calls DB2 export which transfer records to CSV format and after file created and finish transfering then the CSV is zipped.
Continue reading

PHPPageNo Class For Easy Page Numbering Creation

PHP

Brief

PHPPageNo Class helps you to implement page numbering in your PHP application.
This class shows Page No with links to navigate the Page’s Url.
The class constructor have four value settings that you can adjust like $startRec which represents starting record,
$totalRec is total records, $maxRecPerPage is a maximum no of records per page and $maxPageDisplay is a maximum no of page shown.
Anyway you should understand basic of OOP in PHP like constructor, class extends etc in order to get the idea of this post.

The screen shot of how PHPPageNo works is below:

Resulted Page No are also includes Prev and Next links if the total page query is more than $maxPageDisplay.
This makes the page numbering would not be shown like blown list of page no.
Continue reading

PHP Adapter Design Pattern Example

This post contains two examples of Adapter Design Pattern using PHP. I am giving these examples in order to understand more comprehend about Adapter Pattern.

First, implementation of Adapter Design Pattern statement
Convert the interface of a class into another interface clients expect.
Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.
Adapters are helpful if you want to use a class that doesn’t have quite the exact methods you need.

Second, implementation of using legacy class and you can’t change that legacy class but you want to port its method to another needful method.

First Example

An example class ‘clsProducts’ methods can be used inside many Adapter class to returns another result.
clsProducts object instance is passed as Adapter classes constructor argument and clsProducts methods are being used inside those Adapter classes.
Continue reading

Easy Creating Or Convert To PDF File Programmatically Using PHP mPDF

We can create PDF file using PHP easily. I choose mPDF in order to do this. Why mPDF ? That because the method is to use html string for writing PDF content and then produce PDF as an output.
We can format PDF content like an HTML page i.e using bold <b/>, table <table/>, etc which is easy for Web developer off course.

PHP.Net has own recommended PDF creation class which are Haru PDF and PDFLib. They are great but many lines and methods to do simple ‘Hello World’ example. I feel easier using mPDF since it uses HTML string.

This blog post will demonstrate how to install and gives some basic examples so reader can have brief ideas how to create PDF programmatically.

Download & Install MPDF

Download PHP source code of MPDF from http://www.mpdf1.com/mpdf/index.php?page=Download
Copy to a folder in your web server directory. I am using MPDF57 for this demonstration.
Continue reading

Returning Recordset From Oracle Function Under Package Using PHP

Brief

This post shows example of returning recordset from oracle function. The oracle function is stored under Packages folder.
Oracle used version is 11g Express Edition.
This is a simple example. I have a ItemMaster table and then return its records by oracle function and view it on web page.

Example

ItemMaster Table Creation SQL:

CREATE TABLE "HR"."ITEMMASTER" 
   (	"ITEMCODE" VARCHAR2(15 BYTE), 
	"ITEMDESC" VARCHAR2(150 BYTE), 
	"ITEMGROUP" VARCHAR2(15 BYTE), 
	"ITEMTYPE" VARCHAR2(2 BYTE)
   ) SEGMENT CREATION IMMEDIATE 
  PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "USERS" ;

I used default HR sample schema.

Create a package in oracle:

create or replace PACKAGE PCKG_MASTER AS 
FUNCTION LIST_ITEMMASTER RETURN SYS_REFCURSOR;
END PCKG_MASTER;

Continue reading