`return $this;` design pattern or anti-pattern?

前端 未结 5 1578
醉酒成梦
醉酒成梦 2021-01-17 13:22

I\'ve seen many times Zend Framework using return $this; pattern style - and from my point of view:

  • Pro: seems its quite not

5条回答
  •  攒了一身酷
    2021-01-17 13:57

    I've found method chaining to be useful in circumstances where it makes sense; a domain specific language, for example:

    $query->select('*')->from('users')->where(array('user_id' => 1, 'verified' => 1));
    

    The thing is, these methods would only be returning void anyway and so the return $this merely functions as a short hand version of writing:

    $query->select('*'); $query->from('users'); $query->where(...);
    

    We're still going to be calling the toSQL() or execute() method to make use of the data we've populated our object with.

    In my opinion it is not an anti-pattern and can function as a legitimate, sensible, method of object population in the right circumstances.

提交回复
热议问题