Friday, May 31, 2013

PHP N-tier: Introduction N-Tier Strategy


PHP N-tier: Introduction N-Tier Strategy
PHP N-Tier Strategy Step By Step Tutorial - Part 1: May be you face complicated situation in your client's architecture. They use many technology for solve their complicated business process. If it happen, n-tier may be possible one solution you can choice. It this post, we begin to understanding possible N-Tier architecture.
General principle that we must consider if wants to build N-tier application:
  • Every layer must be independent physically. It doesn't mean every layer have to exist in separated computer. But, every layer can be distributed every where (separated computer or not).
  • Each layer must transfer information only to/from previous/next layer.
  • You can change technology used in every layer without change entire system. Example, - you want to change database layer- from mySql to PostgreSQL.
Following sample architecture design use 5-tier:
  • Presentation GUI, do parse HTML, XHTML, WML.
  • Presentation Logic do rendering process HTML, XHTML to send using HTTP to browser. It accepts data from business logic and tie to HTML. This process run at php at web server.
  • Business Logic, manipulate and transform data. Simple, task of this layer is fetch data from data access tier and prepare before send to presentation logic. This process run at server that utilize XML.
  • Data access tier have task to connect and retrieve data from database.
  • Data tier is aplication database such as mySQL, PostGreSQL, and others.

PHP N-tier: Possible n-tier Application Use PHP

PHP N-Tier Strategy Step By Step Tutorial - Part 2: In this post, we will try to design n-tier application use PHP. This is my 5-tier design:
  • Presentation GUI: Using smarty template to generate HTML.
  • Presentation Logic: PHP.
  • Business Logic: Use NuSOAP.
  • Data Access Tier: Using ADOdb.
  • Data tier: Using mySQL.
We ever talked about nusoap, adodb, and mysql. If you still understand about them, please read posts about them.

PHP N-tier: Database Layer Using MySQL

PHP N-Tier Strategy Step By Step Tutorial - Part 3: For practice, we will build simple application to show 5-tier design. We will begin from database layer. At the database layer, we use MySQL.
Create a database, for example "test". Then create table. This is the query:
“CREATE TABLE `books` (
`id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,`title` VARCHAR( 255 ) NOT NULL ,`author` VARCHAR( 60 ) NOT NULL) ENGINE = MYISAM ;
Next, try to insert sample data, such as:
“INSERT INTO `test`.`books` (
`id` ,
`title` ,
`author`
)
VALUES (
NULL , 'PHP Undercover', 'Wiwit Siswoutomo'
), (
NULL , 'PHP Enterprise', 'Wiwit Siswoutomo'
);
Ok, next post we will try how to connect database use PHP ADOdb as data access tier.

PHP N-tier: Data Access Tier Using PHP ADOdb

PHP N-Tier Strategy Step By Step Tutorial - Part 4: In this post, we will build data access tier. We use PHP Adodb. About PHP Adodb, you can read at here.
For this practice, create a folder named "ntier" within www/test. Place your all PHP ADOdb folder at here. Thus, you have www/test/ntier/adodb.
Then create a file named "dataaccess.php" within www/test/ntier. Enter following code
include('adodb/adodb.inc.php');
 $databasetype = 'mysql';
$server = 'localhost';
$user   = 'root';
$password = 'admin';
$database = 'test';
 $db = ADONewConnection($databasetype);
$db->debug = false;
$db->Connect($server, $user, $password, $database);
 $recordSet = &$db->Execute('select * from books');
 if (!$recordSet)
  print $conn->ErrorMsg();
else
  while (!$recordSet->EOF) {
    print $recordSet->fields[0].' '.$recordSet->fields[1].' '.$recordSet->fields[2].'
';
  $recordSet->MoveNext();     
}  
 $recordSet->Close(); # optional
             
$db->Close();
 ?>
Test it. Open your browser. point to http://localhost/test/ntier/dataacces.php.

PHP N-tier: Building Business Logic

PHP N-Tier Strategy Step By Step Tutorial - Part 5: After create connection to database at this post, we will process this data. We prepare this data in order to can to send using webservices. We named this: business logic layer.
This practice only work well for php 4. In php 5, we will talk next serial post. Because there is embedded function in php 5. First, copy library of nusoap within www/test/ntier/lib. If you don't understant to place nusoap, please read this post.
Open again file dataacces.php within www/test/ntier. Update like following:
// call library
require_once ( './lib/nusoap.php' ); //nusoap
require_once ('adodb/adodb.inc.php');//adodb
 // create instance
$server = new soap_server();
 // initialize WSDL support
$server->configureWSDL( 'hello' , 'urn:hellowsdl' );
 // place schema at namespace with prefix tns
$server->wsdl->schemaTargetNamespace = 'urn:hellowsdl';
 // register method
$server->register('books',  // method name
array(), // input parameter
array('return'=>'xsd:array'),
'urn:hellowsdl' , // namespace
'urn:hellowsdl#hello', // soapaction
'rpc', // style
'encoded', // use
'Load list of book to the caller' // documentation
);
 // configuration database
define(__databasetype__,'mysql');
define(__server__,'localhost');
define(__user__,'root');
define(__password__,'admin');
define(__database__,'test');
  // method
function books(){
  $db = ADONewConnection(__databasetype__);
  $db->debug = false;
  $db->Connect(__server__, __user__, __password__, __database__);
   $recordSet = &$db->Execute('select * from books');
   if (!$recordSet){
        return new soap_fault('Server','',$conn->ErrorMsg());
  } else {
    while (!$recordSet->EOF) {
          $books[] = array('id'=>$recordSet->fields[0],
                           'title'=>$recordSet->fields[1],
                                         'author'=>$recordSet->fields[2]
                          );
      $recordSet->MoveNext();     
    }  
     $recordSet->Close();       #optional    
    $db->Close();
  }

  // return value to client
  $obj = new soapval('return','array',$books);
  return $obj->serialize();
 
}
  $HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
?>
Then, test it. Open your browser. Point to http://localhost/test/ntier/dataacces.php. You will get like this:

PHP N-tier: Building Presentation Logic


PHP N-Tier Strategy Step By Step Tutorial - Part 6: After create business logic, now we try to catch the data. We called this: presentation logic layer. We still use nusoap to do this job.
Just for practice, we will create client same folder/location with server function. Create a file named "client_book.php" within www/test/ntier. Enter following code:
require_once ('lib/nusoap.php');
 $client = new soapclient('http://localhost/test/ntier/dataacces.php');
 $response = $client->call('books');
 if($client->fault)
{
  echo "FAULT: Code: (".$client->faultcode.")
";
  echo "String: ".$client->faultstring;
}
else
{
  $r = $response[0];
  $count = count($r);
?>
 
   
     
            
      
   
        for($i=0;$i<=$count-1;$i++){
        ?>
   
     
     
     
   
            }
        ?>
 
IdTitleAuthor

    }
?>
Now, open your browser and point to http://localhost/test/ntier/client_book.php.

PHP N-tier: Building Presentation GUI

PHP N-Tier Strategy Step By Step Tutorial - Part 7: We have grabbed data from server at presentation logic. And we tie data to html at previous post. It will give us more flexible if we you template system. So, we can change any layout without change all. for this job, we use smarty template.
Exactly, what is smarty template? I rewrite from their readme: Smarty is a template engine for PHP. Many other template engines for PHP provide basic variable substitution and dynamic block functionality. Smarty takes a step further to be a "smart" template engine, adding features such as configuration files, template functions, and variable modifiers, and making all of this functionality as easy as possible to use for both programmers and template designers.
First, please download smarty template at smarty.php.net. Extract compressed file to www/test/ntier. You will get folder named like "smarty-2.6.xx". Rename, for simply, become: "smarty".
Then, create folders named "templates" and "templates_c" within www/test/ntier.
Open again your client_book.php, rewrite with this code:
// call library
require_once ('./lib/nusoap.php');
require_once ('./smarty/libs/smarty.class.php');
 // retrieve data from server
// use webservice by nusoap
$client = new soapclient('http://localhost:8048/test/ntier/dataacces.php');
$response = $client->call('books');
 if($client->fault)
{
  echo "FAULT: Code: (".$client->faultcode.")
";
  echo "String: ".$client->faultstring;
  die();
}
else
{
  // start using smarty
  $smarty = new Smarty;

  // assign parameters
  $smarty->assign("title","Books Collection");
  $smarty->assign("books",$response[0]);

  //load template
  $smarty->display('template.tpl');
}
?>
Now, you can see. Your code be more clean. No html tag over there. All html tag will be place at template.
Create a file named "template.tpl" within www/test/ntier/templates. Then enter following code:


{$title}

 
   
     
            
      
   
{foreach key=key item=item from=$books}
   
  {foreach key=key item=item from=$item}
   
  {/foreach}
    
{/foreach}
 
IdTitleAuthor
{$item}
Congrat! you have understand how to build 5-tier use php. You can expand this tutorial as you need.