方法链接PHP OOP

时间:2010-02-21 19:17:03

标签: php oop methods

通常,在许多框架中,您可以找到使用查询构建器创建查询的示例。通常你会看到:

$query->select('field');
$query->from('entity');

但是,在某些框架中,您也可以像这样做

$object->select('field')
       ->from('table')   
       ->where( new Object_Evaluate('x') )
       ->limit(1) 
       ->order('x', 'ASC');

你如何实际做这种链?

3 个答案:

答案 0 :(得分:18)

这称为Fluent Interface - 该页面上有example in PHP

基本思想是每个方法(你希望能够链接)的类必须返回$this - 这样就可以调用同样的其他方法返回$this上的课程。

当然,每个方法都可以访问类的当前实例的属性 - 这意味着每个方法都可以“向当前实例添加一些信息”。

答案 1 :(得分:7)

基本上,你必须让类中的每个方法都返回实例:

<?php

class Object_Evaluate{
    private $x;
    public function __construct($x){
        $this->x = $x;
    }
    public function __toString(){
        return 'condition is ' . $this->x;
    }
}
class Foo{
    public function select($what){
        echo "I'm selecting $what\n";
        return $this;
    }
    public function from($where){
        echo "From $where\n";
        return $this;
    }
    public function where($condition){
        echo "Where $condition\n";
        return $this;
    }
    public function limit($condition){
        echo "Limited by $condition\n";
        return $this;
    }
    public function order($order){
        echo "Order by $order\n";
        return $this;
    }
}

$object = new Foo;

$object->select('something')
       ->from('table')
       ->where( new Object_Evaluate('x') )
       ->limit(1)
       ->order('x');

?>

这通常用作纯粹的眼睛糖果,但我认为它也有其有效的用法。

答案 2 :(得分:2)

class c
{
  function select(...)
  {
    ...
    return $this;
  }
  function from(...)
  {
    ...
    return $this;
  }
  ...
}

$object = new c;