Sabtu, 28 Juni 2014

How to create chaining in PHP

Most of new programmers using the chain method in their code. Actually they just follow the tutorial on the book.

If you are new programmer, you need to read this simple post for better understanding.

After reading this post, I hope you know how chaining works and how to make chaining.

Let start from a case; I use a query case like this;
select id, country_name from country_table order by id desc

Let solve that case.
First, you need to create 'a chaining class';

class MySimpleQuery 
{   
    static public function myQuery()
    {
        return new self();
    }
    
    public function select($field)
    {
        echo "select $field ";
        return $this;
    }

    public function table($table)
    {
        echo "from $table ";
        return $this;
    }
    
    public function order($field,$direction) 
    {
        echo "order by $field $direction ";
        return $this;
    }    
}


Now you want to call it right? This is how to call it;

$my_query = MySimpleQuery::myQuery()
        ->select('id, country_name')
        ->table('country_table')
        ->order('id','desc');
mysql_query($my_query);

If you echoing $my_query, you will see;
select id, country_name from country_table order by id desc

Well, that's it. You can develop above sample towards. 

Tidak ada komentar:

Posting Komentar

Cara Mengetahui Besar Database PostgreSQL Tanpa Mendownloadnya

Berikut adalah langkah-langkah untuk mengetahui ukuran semua database di instance PostgreSQL yang berjalan di dalam kontainer Docker: 1. Men...