Mayur Deore's Blog

Post info:

Clean Code in PHP

This article is about Manageable,Clean coding in PHP.
PHP is one of the most popular Web Development programming language. PHP code in requested file is executed by server, to create dynamic web page content. When I started to develop web sites in PHP, I just wanted things to work in web sites,No matter how I did it. My intention was to complete the task according to the user’s requirement, That’s all most of the beginners want initially,unless someone guide them. There is no problem in that. But you must start to develop yourself, each of your project must be more flexible,manageable than previous one.
Developers thinking depends on how they implement the solution to the specific problem.

For example, consider simple system for student register. Most of the beginner will just start the development on the go. Due to lack of experience or lack of good guidance, even the complete system will not be the flexible, Because of unplanned,messy code. Most of the User’s don’t accept the first build,they will definitely modify their requirement and the system will get more and more complicated. And due to unman-aged,unplanned code frustration rises, So thought about writing this article for those beginners who find it frustrating to develop large scale projects with unmanageable,unplanned code.
So I’m going to provide way to develop simple student information project in PHP in Clean way.

“No one is perfect in this world”, I’m no exception to this. This is my approach, some of you may still find it unmanageable,please let me know about it.

Step 1: DATABASE – Obviously we need storage for saving/retrieving the data. For our project let’s create simple table to store student information.

CREATE TABLE IF NOT EXISTS `student_db` 
(

 `student_id` int(11) NOT NULL,
  
 `name` varchar(200) NOT NULL,
  
 `roll_no` int(11) NOT NULL,
  
 `marks` float NOT NULL

) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;

ALTER TABLE `student_db`
 ADD PRIMARY KEY (`student_id`);
 
ALTER TABLE `student_db`
MODIFY `student_id` int(11) NOT NULL AUTO_INCREMENT;

Step 2:Database Connection I use PDO connection for database connection. It is best to wrap the PDO in class for flexible usability.I use the following class for PDO (source:Stack Overflow).

<?php

class DB {
    
    private $dbh;
    private $stmt;
    private $user="root";//your database username
    private $pass="";//your database password
    private $dbname="student";//your database name

    public function __construct() {
        $this->dbh = new PDO(
            "mysql:host=localhost;dbname=$this->dbname",
            $this->user,
            $this->pass,
            array( PDO::ATTR_PERSISTENT => true )
        );
    }

    public function query($query) {
        $this->stmt = $this->dbh->prepare($query);
        return $this;
    }

    public function bind($pos, $value, $type = null) {

        if( is_null($type) ) {
            switch( true ) {
                case is_int($value):
                    $type = PDO::PARAM_INT;
                    break;
                case is_bool($value):
                    $type = PDO::PARAM_BOOL;
                    break;
                case is_null($value):
                    $type = PDO::PARAM_NULL;
                    break;
                default:
                    $type = PDO::PARAM_STR;
            }
        }

        $this->stmt->bindValue($pos, $value, $type);
        return $this;
    }

    public function execute() {
        return $this->stmt->execute();
    }

    public function resultset() {
        $this->execute();
        return $this->stmt->fetchAll();
    }

    public function single() {
        $this->execute();
        return $this->stmt->fetch();
    }
}

Step 3:Entity Class Create php class for student entity Student.class.php.

<?php

class Student {
    
    public $student_id;
    public $name;
    public $roll_no;
    public $marks;
/**
 * 
 * @param array $row : Select Query result array
 * @return \Student Object
 *  
 */
    public function GetStudentObj(Array $row) {
        
            $this->student_id=$row["student_id"];
            $this->name=$row["name"];
            $this->roll_no=$row["roll_no"];
            $this->marks=$row["marks"];
            return $this;
    }
}

Step 4: Create php class for business logic on student object StudentLogic.class.php.

<?php

/**
 * Business Logic for Student Class goes here
 *
 * @author Mayur Deore
 */
class StudentLogic {
    
    private $db;
    /**
     * 
     * @param DB $dbParam : DB Object
     * 
     */
    public function __construct(DB $dbParam) {
        $this->db=$dbParam;
    }
    /**
     * 
     * @param Student $studObj : Student Class Object
     * @return Number of rows affected
     */
    public function AddStudent(Student $studObj)
    {
        return $this->db->query('INSERT INTO `student_db`(`name`, `roll_no`, `marks`) VALUES (?,?,?)')
                 ->bind(1,$studObj->name)
                 ->bind(2,$studObj->roll_no)
                 ->bind(3,$studObj->marks)
                 ->execute();
    }
    /**
     * 
     * @param Integer $studentId
     * @return Number of rows affected
     * 
     */
    public function DeleteStudent($studentId) {
        return $this->db->query("DELETE FROM student_db WHERE student_id=?")
                ->bind(1,$studentId)
                ->execute();
    }
    /**
     * 
     * @param Student $studObj : Student Object with updated data
     * @return Number of rows affected
     */
    public function UpdateStudent(Student $studObj) {
        
        return $this->db->query("UPDATE student_db SET name=?,roll_no=?,marks=? WHERE student_id=?")
                        ->bind(1, $studObj->name)
                        ->bind(2, $studObj->roll_no)
                        ->bind(3, $studObj->marks)
                        ->bind(4, $studObj->student_id)
                        ->execute();
    }
    /**
     * 
     *  @return array as query result
     */
    public function GetStudents() {
        $row=$this->db->query("SELECT * FROM student_db")
                        ->resultset();
        
        
        
        return $row;
    }
    
    /**
     * 
     * @param Int StudentId
     * @return array as query result
     */
    public function GetStudent($studentId) {
        $row=$this->db->query("SELECT * FROM student_db WHERE student_id=?")
                      ->bind(1, $studentId)
                      ->single();
        return $row;
    }
}

Step 5: Using the class services Now we have all the infrastructure ready, we just need them to use as per requirement.

I. Initialize the objects

<?php
/**
 * 
 * Include and initialize the class objects
 */
require_once './DB.class.php';
require_once './Student.class.php';
require_once './StudentLogic.class.php';

$studObj=new Student();
$studLogic=new StudentLogic(new DB);

?>

II. Add Student.

<?php
/**
 * For Adding Student
 */
$studObj->name="Mayur Deore";
$studObj->roll_no=100;
$studObj->marks=76.86;


if($studLogic->AddStudent($studObj)==1)
{
    echo 'New Student Added';
};

?>

III. Retrieving All Students

<?php
/**
 * 
 * For retrieving All Students
 */
$row=$studLogic->GetStudents();
?>
<table>
    <tr>
        <th>Student ID</th>
        <th>Name</th>
        <th>Roll No</th>
        <th>Marks</th>
    </tr>
<?php
foreach ($row as $singleStudent) {
    
    /*
     * $singleStudent is array of single student info
     * It is best to wrap this information in Student Object
     * 
     */
    $student=$studObj->GetStudentObj($singleStudent); 
    
    ?>

    <tr>
        <td><?php echo $student->student_id; ?></td>
        <td><?php echo $student->name; ?></td>
        <td><?php echo $student->roll_no; ?></td>
        <td><?php echo $student->marks; ?></td>
        
        
    </tr>
<?php

}
?>
</table>   

IV.Updating Student

<?php
/**
 * 
 * For updating student Information
 */
$updateStudentRow=$studLogic->GetStudent(4);
$updateStudent=$studObj->GetStudentObj($updateStudentRow);
$updateStudent->marks=87.99;
if ($studLogic->UpdateStudent($updateStudent)==1) {
    echo 'Student Updated';
}

V.Delete Student

<?php
/**
 * 
 * For Deleting Student using student_id
 */
if ($studLogic->DeleteStudent(4)==1) {
    echo 'Student Deleted.';
}

Now most of you have got idea about clean code in PHP. For any queries/suggestions please comment below.

Mayur Deore

Facebook Twitter LinkedIn 

Leave a Reply

Your email address will not be published. Required fields are marked *