2014-02-21 4 views
0

Как создать класс в PHP, который будет работать как класс DB в codeIgniter?PHP метод() -> метод() -> метод() ->

я могу использовать этот класс таким образом:

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

и так:

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

Спасибо.

+0

Это называется свободно интерфейс/метод цепочки. Его легко реализовать, но вы должны быть уверены, что вам это нужно, поскольку это не всегда считается хорошей практикой. http://ocramius.github.io/blog/fluent-interfaces-are-evil/ –

ответ

8

В своих методах вернуть текущий объект:

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

И, кстати, это называется method chaining.

5

Цепочка как на самом деле довольно проста. Вы просто возвращаете каждый метод $this.

4

Прочитано method chaining.

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

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

$user = new User(); 
$user->first()->second(); 
1

Чтобы использовать «цепочки», и должны вернуть экземпляр класса, например:

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) ; 
Смежные вопросы