Method Chains PHP OOP

不问归期 提交于 2019-12-17 12:47:44

问题


Commonly, in a lot of frameworks, you can find examples of creating a query using the query builder. Often you will see:

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

However, in some frameworks you can also do it like this

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

How do you actually do this kinds of chains?


回答1:


This is called Fluent Interface -- there is an example in PHP on that page.

The basic idea is that each method (that you want to be able to chain) of the class has to return $this -- which makes possible to call other methods of that same class on the returned $this.

And, of course, each method has access to the properties of the current instance of the class -- which means each method can "add some information" to the current instance.




回答2:


Basically, you have to make every method in the class return the instance:

<?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');

?>

This is often used as pure eye candy but I suppose it has its valid usages as well.




回答3:


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

$object = new c;


来源:https://stackoverflow.com/questions/2307097/method-chains-php-oop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!