add

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.

Friday, May 17, 2013

Regex in PHP

1. 1 Character 1 number and string length
^\S*(?=\S{8,})(?=\S*[a-z])(?=\S*[A-Z])(?=\S*[\d])\S*$

  • ^: anchored to beginning of string
  • \S*: any set of characters
  • (?=\S{8,}): of at least length 8
  • (?=\S*[a-z]): containing at least one lowercase letter
  • (?=\S*[A-Z]): and at least one uppercase letter
  • (?=\S*[\d]): and at least one number
  • $: anchored to the end of the string
To include special characters, just add (?=\S*[\W]), which is non-word characters

OR

(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$
   * contain at least (1) upper case letter
   * contain at least (1) lower case letter
   * contain at least (1) number or special character
   * contain at least (8) characters in length



References
1. http://www.autohotkey.com/docs/misc/RegEx-QuickRef.htm
2. http://www.regular-expressions.info/index.html

Zend perks

Zend perks

1. StringLength Validator in Form
$this->addElement('text', 'password', array(
    'label' => 'Password:',
    'required' => true,
    'filters' => array('StringTrim'),
    'validators' => array(
        array('StringLength', false, array(8,20))
    )
));
Another way doing the same thing
$this->addElement('textarea', 'comment', array(  
    'label' => 'Please Comment:',  
    'required' => true,  
    'validators' => array(  
        array('validator' => 'StringLength', 'options' => array(0, 20))  
    )  
)); 

2. Regular expression

To use a regular expression in zend you regex mus b enclosed in (/) like /regex/
$this->addElement('text', 'password', array(
    'label' => 'Password:',
    'required' => true,
    //'filters' => array('StringTrim'),
    'validators' => array(
        array('StringLength', false, array(8,20)),
        array('regex', false, array('pattern' => '/^\S*(?=\S{8,})(?=\S*[a-z])(?=\S*[A-Z])(?=\S*[\d])\S*$/'))
    )
));


Thursday, May 16, 2013

little things BIG time saving (Some important php Functions)



1. array_filter()
simply remove null/empty values froma an array.
$entry = array(
             0 => 'foo',
             1 => false,
             2 => -1,
             3 => null,
             4 => ''
          );
print_r(array_filter($entry));
OutPUT
Array
(
    [0] => foo
    [2] => -1
)

2. readCSV
this function simply takes csv filename(with path) and return an array
function readCSV($csvFile) {
    $file_handle = fopen($csvFile, 'r');
    while (!feof($file_handle)) {
        $line_of_text[] = fgetcsv($file_handle, 1024);
    }
    fclose($file_handle);
    return array_filter($line_of_text);        
}
            

Tuesday, May 7, 2013

Zend Resources


  • Zend Ajax
    • http://blog.jtclark.ca/2010/03/zend-framework-and-ajax/
  • Chained dropdowns 
    • http://www.codeassembly.com/Simple-chained-combobox-plugin-for-jQuery/

Sunday, May 5, 2013

On Sunday 5-5-2013=>
1.Add the form to the page index.php,
  • i have done this by drag and drop form into body of index.php
  • then drag and drop button from html component.
2.Transfer the data to the next php file and named it wishlist.php.

  • use $_GET method for transfering of data from one form to other
3.Create a web page wishlist.php

4.Establish the connection,

Saturday, May 4, 2013

2013 may 05 : starting to learn php

8:00 PM => I started learning php from a tutorial of netbeans.link of the tutorial is https://netbeans.org/kb/docs/php/wish-list-lesson2.html.
here i learnt the following
  1. downloaded netbean
  2. downloaded jdk and installed
  3. downloaded wamp and installed
 9:00 PM => started database connectivity through mysql jdbc in netbeans .
  1. created table of wishers
  2. created table of wishes
  3. inserted data in tables
  4. created simple form and posted its value on next page
 ERROR : I had the following errors

CREATE TABLE wishes2(
 id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
 wisher_id INT NOT NULL,
 description CHAR(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
 due_date DATE,
 FOREIGN KEY (wisher_id) REFERENCES wishers2(id)
)
  1. Error code 1005, SQL state HY000: Can't create table 'saqi.wishes2' (errno: 150)
    Line 1, column 1
  • Solution : error was becuase i did not create the parent table for which i was creating a foreign  key and wishers2 table
10:00 PM