1

I am new to php and crating classes for my project . I have reached this far ..

$db->select('id');
             $db->from('name');
             $db->where("idnum<:num");
             $db->bindparamers(':num',100);
             $rows=$db->executeQuery();

I wana know to create methods such that i can use all thing at once like below

$db->select('id')->from('name')->where('idnum>100')->executeQuery();

I have tried searching but not getting what exactly i should search for

here is my class structure

class Dbconnections
{
    //For Complex Queries
    public function select($items)
    {

    }
    public  function from($tablenames)
    {

    }
    public function where($arr)
    {

    }
    public function orderby($order)
    {

    }
    public function bindparamers($parameter,$value)
    {

    }
    public function executeQuery()
    {}


}

What changes i need to make to use it as :

$db->select('id')->from('name')->where('idnum>100')->executeQuery();
Vikram Sangat
  • 136
  • 11

1 Answers1

4

It's called method chaining and in your case can be achieved by returning $this from each method.

class Dbconnections 
{
    public function select($items)
    {
        // ...
        return $this;
    }
    public  function from($tablenames)
    {
        // ...
        return $this;
    }
    public function where($arr)
    {
        // ...
        return $this;
    }
    public function orderby($order)
    {
        // ...
        return $this;
    }
    public function bindparamers($parameter,$value)
    {
        // ...
        return $this;
    }
    public function executeQuery()
    {
        // ...
        return $this;
    }
}
Shoe
  • 74,840
  • 36
  • 166
  • 272
  • 3
    It's called *fluent interface* ;) – hek2mgl Jan 18 '14 at 08:19
  • @Jefffrey your solutiong works perfertly fine . But now that is i dont want to create all methods as my chaining methods like : i want only 2 methods to be chained for select() ex. `$db->select()->from()->where()` and if i am doing update then `$db->update()->set()->where()` like wise i only need to make where as my global chaing and from and set will be dependent on select and update is that possible ? – Vikram Sangat Jan 18 '14 at 13:36
  • @VikramSangat, you should open another question for that. – Shoe Jan 18 '14 at 14:03