方法链接PHP OOP

Lay*_*yke 12 php oop methods

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

$query->select('field');
$query->from('entity');
Run Code Online (Sandbox Code Playgroud)

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

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

你怎么实际做这种链?

Pas*_*TIN 18

这称为Fluent Interface - 该页面上有一个PHP示例.

基本思想是类的每个方法(你希望能够链接)都必须返回$this- 这使得在返回的类中调用同一个类的其他方法成为可能$this.

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


Álv*_*lez 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');

?>
Run Code Online (Sandbox Code Playgroud)

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