PHP – Learning OOP PHP with Java Style

Saya sebenarnya bukan programmer yang familiar dengan PHP.
Pengetahuan saya tentang PHP masih sangat dangkal, jadi bila di postingan ini terdapat beberapa kesalahan mohon dikoreksi.

Selagi saya mencari-cari bahan untuk belajar dasar-dasar PHP, saya menemukan tutorial ini : https://www.codeofaninja.com/2014/06/php-object-oriented-crud-example-oop.html
Dan saya rasa cara si penulis blog tersebut sangat menjabarkan PHP sangat enak dan sesuai dengan saya yang pada awalnya belajar Java karena codingan-nya ditulis dengan OOP (Object Oriented Programming).

Saya coba baca dan sedikit saya manipulasi dengan style saya sendiri, file source juga bisa di download secara gratis pada akhir tulisan ini.


Semua code bisa dilihat di github saya : https://github.com/mazipan/learn-php-oop-like-java

Berikut saya jelaskan sedikit saja, sisanya silahkan baca sendiri dari file source yang saya bagikan :

1. Buat Class Category

<?php
class Category{
  
    // object properties
    public $id;
    public $name;
	
	// getter & setter
	function setId($par){
       $this->id = $par;
    }
    function getId(){
       return $this->id;
    }
	function setName($par){
       $this->name = $par;
    }
    function getName(){
       return $this->name;
    }
	
    // overide toSting method    
    public function __toString(){
        return "Category -> [id:".$this->id.", name:".$this->name."]</br>";
    }   
}
?>

2. Buat Interface untuk Category

<?php
interface CategoryInterface {
    
   public function selectAll($conn);
   public function selectByIdReturnJson($conn, $id);
   public function update($conn, $cat);
   public function insert($conn, $category_name);
   public function delete($conn, $id);

}
?>

3. Buat class DAO untuk category yang merupakan implament dari interface diatas

<?php

include_once '../model/interface/i_category.php';
include_once '../model/category.php';

class CategoryDAO implements CategoryInterface{
    
    public function selectAll($conn) {       
        $result = $conn->query("SELECT * FROM categories ORDER BY name");  
        $categories = array();
        if($result->num_rows > 0){
            $index = 0;
             while($row = $result->fetch_assoc()) {
                $cat = new Category();
                
                $cat->setId($row["id"]);
                $cat->setName($row["name"]);
                
                $categories[$index] = $cat;                
                $index++;
            }
        }
        
        $result->close();
        $conn->close();  
        
        return $categories;    
    }
    
    public function selectByIdReturnJson($conn, $id) {        
        $stmt = $conn->prepare("SELECT * FROM categories WHERE id = ?");
        $stmt->bind_param('i', $id);
        
        $stmt->execute();
        
        $cat = new Category();
        $stmt->bind_result($idResult, $nameResult, $created, $modified);
        
        while ($stmt->fetch()) {
           $cat->setId($idResult);
           $cat->setName($nameResult);
        }
        
        $stmt->close();
        $conn->close();
        
        return json_encode($cat);        
    }
    
    public function update($conn, $cat) {        
        $stmt = $conn->prepare("UPDATE categories SET categories.name = ?, categories.modified = CURRENT_TIMESTAMP WHERE id = ?");  
        $stmt->bind_param('si', $cat->getName(), $cat->getId());       
   
        $stmt->execute();
        
        if($stmt->error != ''){
            $result = array("result" => $stmt->error); 
        }else{
            $result = array("result" => "success"); 
        }    
        
        $stmt->close();
        $conn->close(); 
        
        return json_encode($result);
    }
    
    public function insert($conn, $category_name) {
        $stmt = $conn->prepare("INSERT INTO categories VALUES (NULL, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)");  
        $stmt->bind_param('s', $category_name);       
   
        $stmt->execute();
        
        if($stmt->error != ''){
            $result = array("result" => $stmt->error); 
        }else{
            $result = array("result" => "success"); 
        }    
        
        $stmt->close();
        $conn->close(); 
        
        return json_encode($result);
    }

    public function delete($conn, $id) {
        $stmt = $conn->prepare("DELETE FROM categories WHERE id = ?");  
        $stmt->bind_param('i', $id);
   
        $stmt->execute();
        
        if($stmt->error != ''){
            $result = array("result" => $stmt->error); 
        }else{
            $result = array("result" => "success"); 
        }    
        
        $stmt->close();
        $conn->close(); 
        
        return json_encode($result);
    }

}
?>

4. Tinggal bikin view untuk memanggil DAO tersebut, berikut adalah potongan codingan untuk view.

<?php
                // include depedency file
                include_once '../config/database.php'; 
				include_once '../model/dao/categoryDAO.php';
                
                // get database connection
                $database = new Database();
                $db = $database->getConnection();
                
				// read categories from the database
                $dao = new CategoryDAO();
                $stmt = $dao->selectAll($db);
                $no = 1;
                foreach($stmt as $value){
                    
                    echo '<tr><td class="col-md-1">'.$no.'</td>';
                    echo '<td class="col-md-6">'.$value->getName().'</td>';
                    echo '<td class="col-md-2">';
                    echo '<button type="submit" class="btn btn-primary" onclick="getCategory('.$value->getId().')">';
                    echo '      <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span> Edit';
                    echo '</button>';
                    echo '&#09';
                    echo '<button type="submit" class="btn btn-primary" onclick="deleteCategory('.$value->getId().')">';
                    echo '      <span class="glyphicon glyphicon-trash" aria-hidden="true"></span> Delete';
                    echo '</button>';
                    echo '</td></tr>';
                    $no++;
                }               
				?>

Download Source Code https://github.com/mazipan/learn-php-oop-like-java atau via 4 shared.

Terima kasih dan semoga bermanfaat.

mazipan-signature

2 thoughts on “PHP – Learning OOP PHP with Java Style

Be a good reader, leave your comment please.

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s