0

How can I create Class in PHP, which will work like DB Class in codeIgniter ?

I can use this class in such a way:

$this->db->select('...');
$this->db->where('...');
$this->db->get('...');

and like that:

$this->db->select('...')->where('...')->get('...')-> .......

Thanks.

mtoy
  • 197
  • 2
  • 12
  • That is called a fluent interface / method chaining. Its easy to implement, but you have to be sure that you need it, since it is not always considered a good practice. http://ocramius.github.io/blog/fluent-interfaces-are-evil/ – Carlos Robles Feb 21 '14 at 15:31

4 Answers4

8

In your methods return your current object:

public function method() {
    // ...
    return $this;
}

And by the way, it's called method chaining.

evuez
  • 3,257
  • 4
  • 29
  • 44
5

Chaining like that is actually quite simple. You simply have each method return $this.

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
4

Read method chaining.

class User
{
   public function first()
   {
       return $this;
   }

   public function second()
   {
       return $this;
   }
}

$user = new User();
$user->first()->second();
Brice
  • 1,026
  • 9
  • 20
1

To you use the 'chaining', u should return the instance of the class, like this:

class Sql {

    protected $select ;
    protected $where ;
    protected $order ;

    public function select( $select ) {
        $this->select = $select ;
        //this is the secret
        return $this ;
    }

    public function where( $where ) {
        $this->where = $where ;
        //this is the secret
        return $this ;
    }

    public function order( $order ) {
        $this->order = $order ;
        //this is the secret
        return $this ;
    }

}

$sql = new Sql() ;

$sql->select( "MY_TABLE" )->where( "ID = 10" )->order( "name" ) ;

var_dump( $sql ) ;