Monday 16 May 2016

Project Documentation

We are going to Build below html form, instate of using traditional way we are now going to learn Advance Documentation structure. 

Author Master
Author Name:
Author Degree:
Author Speciality:
Author DOB:
 

Author NameAuthor DegreeSpecialityDate Of Birth
DharmarajM.TechOpen Source Product23/06/1985
Raj PanigrahiMCAAnalyst Designer02/06/1987

This form will allow: 
  • Inserting data into the AuthorMaster
  • Updating data already exiting in the AuthorMaster
  • Viewing of data available in AuthorMaster
  • Deleting data from AuthorMaster

File Include
PHPdosql.phpPerforms the insert,delete and update operations
JavaScriptN/A
J-QueryN/A
CSSN/A


Function Declared
PHPN/A
JavaScriptsetEditMode(),setMode(),setDelMode(),chkBlanks()


Form Details
Form NamefrmAuthMast
Form TitleAuthor Master
Bound Tobookdb.AuthorMaster


Data Fields
ObjectLabelNameIdBound To
HiddenN/AhidAuthIdN/AN/A
HiddenN/AhidModeN/AN/A
HiddenN/AhidSelDelN/AN/A
LabelAuthor NameN/AN/AN/A
LabelAuthor DegreeN/AN/AN/A
LabelSpecialitN/AN/AN/A
LabelDate Of BirthN/AN/AN/A
Text BoxAuthorIdtxtAuthIdN/AAuthorMaster.AuthorID
Text BoxAuthorNametxtAuthNameN/AAuthorMaster.AuthorName
Text BoxAuthorDegreetxtAuthDegreeN/AAuthorMaster.AuthorDegree
Text BoxSpecialitytxtSpecialityN/AAuthorMaster.Speciality
Text BoxDOBtxtDOBN/AAuthorMaster.DOB
CheckBoxN/Achk<AuthorID>N/A(AuthorMaster.AuthorID)'s value


Data Controls
ObjectObjectLabelIdAction
ButtoneSavecmdSubmitN/AJavaScript:onSubmit()
ButtoneCancelcmdResetN/AJavaScript:setEditMode()
ButtoneDeletecmdDeleteN/AJavaScript:setDelMode()




1.Commented Statement provide a description and purpose of the file. 

/* 
Date :- 13/02/2011 
Author :- Dharmaraj Panigrahi 
File Name :- AuthorMaster.php 
Purpose :- This page provides an interface to manage author details.

It allows 
Adding new Author Details.
Viewing Author Details.
Updating and existing Author's Details.
Deleting and existing Authors's Details.
*/


2.Common PHP Variablse
/*
A Variable named $author holding the name of the programmer who designed/coded the page.
*/
$author = 'Dharmaraj Panigrahi';



3.PHP Variable bound to Database Connection
$user = "root";
$pwd = "pass";
$db = "bookdb";
$host = "localhost";



4.PHP Code block to establish a Database Connection
mysql_connect($user,$pwd,$host) or die("Connection Failed");
mysql_select_db($db) or die("Could not select the database");



5.The code block taht display the actual HTML page begins



6.Body Section



7.Script tag holding under the body section



7.1.JavaScript function to set contents of form fields.
function setEditMode(AuthorID,AuthorName,AuthorDegreee,Speciality,DOB)
{
.....
}//end of setEditMode function



7.2.JavaScript function to Clear the form fields.
function setMode()
{
.....
}//end of setMode() function



7.3.JavaScript function to Prepare the form to delete selected record.
function setDelMode()
{
.....
}//end of setDelMode() function



7.4.JavaScript function to Delete a string of data retrived.
function formDeleteValues(hidden)
{
.....
}//end of formDeleteValues() function



7.5.JavaScript function to Varifay form fields are not left empty.
function chkBlanks()
{
.....
}//end of chkBlanks() function



7.6.Script tag end.



8.Form Section holding Data and control objects begins.



9.Parent Table begins.



10.PHP Code bloce to retrive records from AuthorMaster table.



11.Second Chield table to ost the tabular layout(GRID), to display/control data captured begins.



12.Second Child table->First Row:
Columns to hold the header row along with the Delete button.



13.PHP Code block to populate data in the tabular layout using a loop.



14.Second Chield table -> Second Row:
Columns to set data and assign colors to odd and even rows.



15.Loop and the Second Child table ends.



16.The mysql connection is closed and the parent table ends.



17.Form to host Data and control objects ends.



18.HTML code block along with BODY section rendering the actual page ends.

To be continued.....

Object Oriented Programming Concepts With MySql Data Base

Developers who have already written code to get data in and out of the mysql database, but who wish to discoverif there are any benefits of adopting an Object Oriented approch.

This exercise will help in:

  • Defining a class with properties and methods.
  • Creating an object (an instance) of class.
  • Creating a class which extends another class.
  • Communicating with an object from within a PHP script.

The focus is to develop a class that can be used in applications that require connectivity and interaction with the MySql Db engine.

CLASS NAMEdharmarajDbClass
ConstantsMYSQL_TYPES_NUMERIC
MYSQL_TYPES_DATE
MYSQL_TYPES_STRING
Properties
Methods
Parameters
Purpose
last_error__construct()N/A 
last_queryconnect()host, user, pw, db, persistantTo establish a Connection with MySql Db server. Also allows selecting a start up database.
row_countselect_db()dbMySql database name for selectionTo select a database to work with. this can be called when it is desired to work a different Db.
hostselect()sqlAn Sql queryTo execute an SQL query passed as a parameter.This function returns the result pointere.
userselect_one()sqlAn Sql queryPerforms an SQL query to return only ONE column and one result.
pwget_row()$resultA result pointer returned after query executation.To retrieve a row of data from the query result set.
$typeMYSQL_ASSOC or MYSQL_NUM or MYSQL_BOTH(Default)
dbdump_query()sqlAn Sql queryTo display the query result in table format.
db_linkinsert_sql()sqlAn Sql queryTo accept an Insert SQL statement and fire the same against the database.
auto_slashesupdate_sql()sqlAn Sql queryTo accept and UPDATE SQL statement and fire the same against the database.
 insert_array()$tableThe table name to which the INSERT will be fired.To inserte data accepted (as a parameter) in form of an array to a specific Db table (accepted as a parameter).
$dataThe array holding values (to be inserted).
 update_array()$tableThe table name against which the Update will be fired.To update data accepted (as a parameter) in form of an array against a specific Db table (accepted as a parameter) based on a specific condition (accepted as a parameter) 
$dataThe array holding values (to be updated)
$conditionA WHERE clause condition that can be applied to the UPDATE SQL statement.
 execute_file()$fileThe file name (along with path if required) holding the SQL commands.To execute SQL commands held inside an external file.
 get_column_type()$tableThe table name to which INSERT will be fired.To determine the data type of a particular column.
$columbThe column name whose data type has to determiner.
 sql_date_format()$valueThe data srtingTo convert a string to a data formate for insertion in the database.
 print_last_error()$show_queryIf this holds true the last query that was executed is also displayed along.sTo print the last error to the screen.
 print_last_query()NONETo display the last query that was executed.
    

The following code spec creats a Class named dharmarajDbClass in dbClass.php file. 
To be Continued....


Simple, non-OOP programs may be one "long" list of statements (or commands). More complex programs will often group smaller sections of these statements into functions or subroutines each of which might perform a particular task. With designs of this sort, it is common for some of the program's data to be 'global', i.e. accessible from any part of the program. As programs grow in size, allowing any function to modify any piece of data means that bugs can have wide-reaching effects.

In contrast, the object-oriented approach encourages the programmer to place data where it is not directly accessible by the rest of the program. Instead, the data is accessed by calling specially written functions, commonly called methods, which are either bundled in with the data or inherited from "class objects." These act as the intermediaries for retrieving or modifying the data they control. The programming construct that combines data with a set of methods for accessing and managing those data is called an object. The practice of using subroutines to examine or modify certain kinds of data, however, was also quite commonly used in non-OOP modular programming, well before the widespread use of object-oriented programming.

An object-oriented program will usually contain different types of objects, each type corresponding to a particular kind of complex data to be managed or perhaps to a real-world object or concept such as a bank account, a hockey player, or a bulldozer. A program might well contain multiple copies of each type of object, one for each of the real-world objects the program is dealing with. For instance, there could be one bank account object for each real-world account at a particular bank. Each copy of the bank account object would be alike in the methods it offers for manipulating or reading its data, but the data inside each object would differ reflecting the different history of each account.

Objects can be thought of as wrapping their data within a set of functions designed to ensure that the data are used appropriately, and to assist in that use. The object's methods will typically include checks and safeguards that are specific to the types of data the object contains. An object can also offer simple-to-use, standardized methods for performing particular operations on its data, while concealing the specifics of how those tasks are accomplished. In this way alterations can be made to the internal structure or methods of an object without requiring that the rest of the program be modified. This approach can also be used to offer standardized methods across different types of objects. As an example, several different types of objects might offer print methods. Each type of object might implement that print method in a different way, reflecting the different kinds of data each contains, but all the different print methods might be called in the same standardized manner from elsewhere in the program. These features become especially useful when more than one programmer is contributing code to a project or when the goal is to reuse code between projects.

Object Oriented Programming Concepts

1.Basic Class Declearation and object initilization
Out Put of the above code

Hello My PHP Class
2.Construter and Destruct
Out Put of the above code

MySql 5 for Professional
Destruct used to destry property of the calss
using php 5.1
Destruct used to destry property of the calss
3.Understand const key ward
Out Put of the above code

Using PHP 5.1 For Professional
Dharmaraj
Lavan Bayross
4.This Key Word
Out Put of the above code

The discount for the bookMy name is Dharmaraj is RS100
5.Scope Resolution Operator(::)
Out Put of the above code

The Scope resolution operator is a token that allows access to static, constant, and overridden members or methods of a class
MY Using PHP 5.1 for professionals
6.Self and Parent keywords
Out Put of the above code

self refers to the current class and it is usually used to access static memebers,methods,constants
parent refers to the parent class and it is monst often used when wanting to call the parent constructor or methods.
Using php 5.1 for oops
Book:Using php 5.1 for oops
Author1:Dharmaraj Panigrahi
Author2:My self

7.Extending A Class
Out Put of the above code

Extending enables inheriting from a parent class, inheriting all its methods and properties and thus creating an IS A RELATIONSHIP
Book Nameusing my own extend class
Publisher NameSPD

8.Class Abstration
Out Put of the above code

Creating an instance of a class that has been defined asabstract is not allowed
Any class that contains at least one abstract method must also be abstract
when inheriting from an abstract class, the child must be define all methodes marked abstract in the parents class declaration
First Book
My Sql 5 for professional
Second Book
Using PHP 5.1 For Professionalss
9.Object Interface
Out Put of the above code

Interface are defined using interface keyword in the same way as a standard class but With out any of the methods having any signatures
All method declaed in an interface must be public as this is the nature of an interface
10.Implements Keyword
Out Put of the above code

All methods in the interface must be implemented within a class, failure to do so will result in a fatal error
Class may implement more than one interface
Dharmaraj
Panigrahi

11.Object Cloning
Out Put of the above code

Hello World
Hello World

12.Final Keyword Final Methods
Out Put of the above code

A method can not be re-implemented in its derived class. The declares the method as a final versio, which cannot be overridden
This Script would not wodrk because by defining MoreTest() as final in BaseClass, this script will result in a fatal error

13.Final Keyword for Final Class
Out Put of the above code

Similar to the final method one can also define final class Doing so disallows inheriting from this class
This Script would not wodrk 

14.Magic Methodes

The function names __construct,__destruct,__call,__get,__set,__isset,__unset,__sleep,__wakeup,__toString,__set_state,__clone and __autoload are magical in PHP classes. 

15.__sleep and __wakeup Methods
Out Put of the above code


The wake up function called

16.Object Comparison
Out Put of the above code

Two object instances are equal if they have the same attributes and values and
Two object instances are instances of the same class
Comparison operator(==) and identity operator (===) when useing identity operator object variabses are identical if and only if they refer to the same instance of the same class.Two instances of the same class
str1 == str2:TRUE
str1 === str2:FALSE
Two Referance to the same instance
str1 == str2:TRUE
str1 === str2:TRUE
Instances of Two Different class
str1 == str2:FALSE
str1 === str2:FALSE



About

Simple, non-OOP programs may be one "long" list of statements (or commands). More complex programs will often group smaller sections of these statements into functions or subroutines each of which might perform a particular task. With designs of this sort, it is common for some of the program's data to be 'global', i.e. accessible from any part of the program. As programs grow in size, allowing any function to modify any piece of data means that bugs can have wide-reaching effects.

In contrast, the object-oriented approach encourages the programmer to place data where it is not directly accessible by the rest of the program. Instead, the data is accessed by calling specially written functions, commonly called methods, which are either bundled in with the data or inherited from "class objects." These act as the intermediaries for retrieving or modifying the data they control. The programming construct that combines data with a set of methods for accessing and managing those data is called an object. The practice of using subroutines to examine or modify certain kinds of data, however, was also quite commonly used in non-OOP modular programming, well before the widespread use of object-oriented programming.

An object-oriented program will usually contain different types of objects, each type corresponding to a particular kind of complex data to be managed or perhaps to a real-world object or concept such as a bank account, a hockey player, or a bulldozer. A program might well contain multiple copies of each type of object, one for each of the real-world objects the program is dealing with. For instance, there could be one bank account object for each real-world account at a particular bank. Each copy of the bank account object would be alike in the methods it offers for manipulating or reading its data, but the data inside each object would differ reflecting the different history of each account.

Objects can be thought of as wrapping their data within a set of functions designed to ensure that the data are used appropriately, and to assist in that use. The object's methods will typically include checks and safeguards that are specific to the types of data the object contains. An object can also offer simple-to-use, standardized methods for performing particular operations on its data, while concealing the specifics of how those tasks are accomplished. In this way alterations can be made to the internal structure or methods of an object without requiring that the rest of the program be modified. This approach can also be used to offer standardized methods across different types of objects. As an example, several different types of objects might offer print methods. Each type of object might implement that print method in a different way, reflecting the different kinds of data each contains, but all the different print methods might be called in the same standardized manner from elsewhere in the program. These features become especially useful when more than one programmer is contributing code to a project or when the goal is to reuse code between projects.

1.Basic Class Declearation and object initilization

//create an object of MyClass
     $clsObject = new MyClass();
     $clsObject->setData("Hello My PHP Class");
     print $clsObject->getData()."<br>";
     
     class MyClass
     {
        public $everyOnceData;
        private $myData;
        protected $myCounter;
        //setter
        public function setData($data)
        {
            $this->myData=$data;
        }//end of function setData()
        //getter
        public function getData()
        {
            return $this->myData;
        }//end of function getData()
     }//end of MyClass



2.Construter and Destruct

class Book
   {
       private $name;
       
       //constructer function
       function __construct($name)
       {
          $this->name = $name;
       }//end of __construct()
       
       //making a destructor
       function __destruct()
       {
         $this->name = NULL;
         print "Destruct used to destry property of the calss";
       }//end of function __destruct()
       function getName()
       {
          return $this->name;
       }//end of gerName()
   }//ebd if Book Class

     //create an object of Book class
     $firstBook = new Book("MySql 5 for Professional");
     $secondBook = new Book("using php 5.1");

     print $firstBook->getName()."<br>";
     $firstBook=NULL;
     print"<br>";
     print $secondBook->getName()."<br>";
     $secondBook=NULL;
     print"<br>";

3.Understand const key ward

class constBook
   {
      const NAME = "Using PHP 5.1 For Professional";
      const AUTHOR1 = "Dharmaraj";
      const AURHOR2 = "Lavan Bayross";
      
      function printBook()
      {
         echo self::NAME."<br>";
         echo self::AUTHOR1."<br>";
      }//end of function printBook
   }//end of constBook


     $obj=new constBook();
     $obj->printBook();
     echo constBook::AURHOR2;
     print"<br>";

4.This Key Word

class Display
   {
      public $name ="My name is Dharmaraj ";
      public $price = "500";
      
      public function Calculate($discount)
      {
         echo "The discount for the book".$this->name."is RS".$discount;
         $this->price-=$discount;
         
      }//end of function Calculate
   }//end of class

     $obj=new Display();
     $obj->Calculate(100);
     print"<br>";

5.Scope Resolution Operator(::)

class myBook
     {
        const NAME ="MY Using PHP 5.1 for professionals";
     }//end of class myBook
     echo myBook::NAME;

6.Self and Parent keywords

class myFebBook
     {
        const NAME ="Using php 5.1 for oops";
     }//end of myFebBook
     echo myFebBook::NAME;
     print"<br>";
     class Author extends myFebBook
     {
        public static $author1 ="Dharmaraj Panigrahi";
        public static $author2 ="My self";

        public static function getNames()
        {
           echo "Book:" . parent::NAME."<br>";
           echo "Author1:".self::$author1."<br>";
           echo "Author2:".self::$author2."<br>";
        }//end of function getNames()
     }//end of Author class

     Author::getNames();

7.Extending A Class

class myTestBook
     {
        public $book;
        function getBook()
        {
          return $this->book;
        }//end of getBook()
        function setBook($myBook)
        {
          $this->book = $myBook;
        }//end of setBook
     }//end of myTestBook
     
     class publishedBook extends myTestBook
     {
         public $publisher;

         function getPublisher()
         {
            return $this->publisher;
         }//end of getPublisher()
         function setPublisher($myPublisher)
         {
            $this->publisher=$myPublisher;
         }//end of function setPublisher()
     }//end of publishedBook
     
     $obj=new publishedBook();
     $obj->setBook("using my own extend class");
     $obj->setPublisher("SPD");
     
     echo "Book Name".$obj->getBook()."<br>";
     echo "Publisher Name".$obj->getPublisher()."<br>";

8.Class Abstration

 abstract class AbstractBook
           {
              abstract protected function getValue();
              abstract protected function prefixValue($prefix);

              public function printOut()
              {
                  print $this->GetValue()."<br>";
              }//end of function printOut()

           }//end of abstract class AbstractBook

           class FirstBook extends AbstractBook
           {
                protected function getValue()
                {
                    return "First Book";
                }//end of getValue()

                public function prefixValue($prefix)
                {
                    return "{$prefix}";
                }//end of prefixValue($prefix)
           }//end of FirstBook

           class SecondBook extends AbstractBook
           {
               public function getValue()
               {
                   return "Second Book";
               }//end of getValue()

               public function prefixValue($prefix)
               {
                   return "{$prefix}";
               }//end of prefixValue($prefix)
           }//end of class SecondBook

           //creating objects class
           $class1 = new FirstBook;
           $class1->printOut();
           echo $class1->prefixValue("My Sql 5 for  professional")."<br>";
           
           $class2 = new SecondBook;
           $class2->printOut();
           echo $class2->prefixValue("Using PHP 5.1 For Professionalss")."<br>";

9.Object Interface 

interface Book_one
        {
        public function getVariable();
        }//end of interface Book

10.Implements Keyword

interface my_Book
           {
               public function getVariable();
               const FIRSTNAME = "Dharmaraj";
               const SECONDNAME = "Panigrahi";
           }//end of book interface

           class Template implements my_Book
           {
              public function getVariable()
              {
                  echo my_Book::FIRSTNAME."<BR>";
                  echo my_Book::SECONDNAME."<BR>";
              }//end of function getVariable
           }//end of Template

           $obj = new Template();
           $obj->getVariable();

11.Object Cloning 

class SubObject
           {
               public function __construct()
               {
                 echo "Hello World"."<br>";
               }//end of function __construct()
               public function __clone()
               {

               }//end of __clone()
           }//end of SubObject class
           
           class CloneClass
           {
              public $obj1;
              public $obj2;
              
              function __clone()
              {
                  $this->obj1 = clone($this->obj1);
              }//end of __clone function
           }//end of CloneClass
           
           $object = new CloneClass();
           $object->obj1 = new SubObject();
           $object->obj2 = new SubObject();
           $object2 = clone $object;

12.Final Keyword Final Methods

class BaseClass
              {
                 public function Test()
                 {
                    echo "BaseClass::Test() called<br>";
                 }//end of test function
                 final public function MoreTest()
                 {
                    echo "BaseClass::MoreTest() called<br>";
                 }//end of MoreTest
              }//end of BaseClass
              
              class ChildClass extends BaseClass
              {
                 public function MoreTest()
                 {
                    echo "ChildClass::MoreTest()callec<br>";
                 }//end of MoreTest
              }//end of ChildClass

13.Final Keyword for Final Class

final class BaseClass
              {
                 public function Test()
                 {
                    echo "BaseClass::Test() called<br>";
                 }//end of test function
                 final public function MoreTest()
                 {
                    echo "BaseClass::MoreTest() called<br>";
                 }//end of MoreTest
              }//end of BaseClass
              
              class ChildClass extends BaseClass
              {
                 public function MoreTest()
                 {
                    echo "ChildClass::MoreTest()callec<br>";
                 }//end of MoreTest
              }//end of ChildClass

14.Magic Methodes 

     The function names __construct,__destruct,__call,__get,__set,__isset,__unset,__sleep,__wakeup,__toString,__set_state,__clone and __autoload are magical in PHP classes.


15.__sleep and __wakeup Methods

class Connection
           {
               protected $dbcon;
               private $host,$username,$password;
               
               public function dbcon()
               {
                   $this->connect("localhost","root","");
               }//end of function dbcon()

               private function connect($host,$username,$password)
               {
                   $this->host=$host;
                   $this->username=$username;
                   $this->password=$password;

                   $this->dbcon = mysql_connect($this->host,$this->username,$this->password);
                   echo "The connection to Mysql estadblished"."<br>";
                   $this->__sleep();
               }//end of connect function

               public function __sleep()
               {
                  mysql_close($this->dbcon);
                  echo "The connection to MySql is closed"."<br>";
               }//end of __sleep function

               public function __wakeup()
               {
                  $this->connect("localhost","root","");
               }//end of function __wakeup()

           }//end of class Connection
           
           $obj = new Connection();
           $obj -> dbcon();
           echo "<br>The wake up function called"."<br>";
           $obj->__wakeup();

16.Object Comparison

function boolstr($bool)
      {
      if ($bool === false)
      {
      return 'FALSE';
      }//end of if statement
      else
      {
      return 'TRUE';
      }//end of else statement
      }//end of boolstr function
      function compareObjects(&$str1,&$str2)
      {
      echo 'str1 == str2:'.boolstr($str1 == $str2)."<br>";
      echo 'str1 === str2:'.boolstr($str1 === $str2)."<br>";
      }//end of compareObjects()
     
      class Flag
      {
      public $flag;
     
      function Flag($flag = true)
      {
      $this->flag=$flag;
      }//end of Flag function
      }//end of Flag class
     
      class OtherFlag
      {
      public $flag;
      function OtherFlag($flag = true)
      {
      $this->flag=$flag;
      }//end of OtherFlag function
      }//end of OtherFlag
     
      $o = new Flag();
      $p = new Flag();
      $q = $o;
      $r = new OtherFlag();
     
      echo "Two instances of the same class<br>";
      compareObjects($o,$p);
     
      echo "Two Referance to the same instance<br>";
      compareObjects($o,$q);
     
      echo "Instances of Two Different class<br>";
      compareObjects($o,$r);