2010-02-21 86 views
12

通常,在很多框架中,可以找到使用查询构建器创建查询的示例。通常你会看到:方法链PHP OOP

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

然而,在一些框架也可以做这样的

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

你如何真正做到这一点种类链?

回答

18

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

的基本思路是,每种方法(要能够链)之类的必须返回$this - 这就有可能呼吁返回$this同一类的其他方法。

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

+0

不客气:-) ;;是的,每种方法都可以设置/更改属性,而“最后”方法通常用于“执行”任何前面调用的方法进行配置。 – 2010-02-21 19:23:43

+0

不确定使用流畅的界面会使代码更易于阅读;;;例如,当它用于构建一些SQL查询时,它是有道理的;但是当方法没有真正相关时,不太确定 - 取决于情况,我想;;;一件好事就是即使你的方法返回'$ this',他们也可以被称为“典型的方式”。 – 2010-02-21 19:25:17

+0

它是否必须返回'$ this'?它不能返回'$ that'并从那里继续? – 2014-04-07 17:16:46

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

$object = new c; 
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'); 

?> 

这通常被用来作为纯眼睛糖果,但我想它有它的用途有效,以及。

+0

用例:'$ setup = $ Object-> add_component($ component_property) - > configure($ component_properties);'Object Object :: add_component()返回它作为$ Object属性添加的Component对象(例如,数组),并使用Component :: configure()方法进行配置。如果没有链接,我们必须确定添加到$ Object-> Components数组的最后一个元素,然后以这种方式获取Component对象。 – AVProgrammer 2012-09-21 00:32:11

+0

@AVProgrammer - 你的例子没有使用'return $ this',是吗? – 2012-09-22 19:09:21

+0

是的,Component对象执行此操作以允许configure()方法。 – AVProgrammer 2012-09-24 20:57:22