Is there a certain way to chain methods in PHP?

79 Views Asked by At

I've been doing method chaining for quite some time, and it seems like the more I add to the dynamic approach of chaining, the more it gets like a big mess, such as adding a new feature to chains then has to work with all other types of chains.

Currently, I've dropped some older projects to re-write them in a more simpler fashion, what I'm working on currently is:

$psm->select('users')->where('id = 1')->run(function($row){
  // do code
});

Which works well, it creates statements dynamically (dynamic as in I could add another chain in the middle to create another clause in the statement.

What I'm wondering is if there's a certain structure to follow when creating chainable methods, because of course, you need to in the end return $this unless running the last method.

My current bare-bones structure in my head for creating chainable classes is as follows:

class foo {
  public $temporary = '';        

  public function add($string) {
    $this->temporary .= $string;
    return $this;
  }
  public function ret() {
    return $this->temporary;
  }
}

So, when running

$foo = new foo;
echo $foo->add('hello ')->add('world!')->ret();

It outputs "hello world!" as you'd expect, but are there better approaches to creating chainable OOP methods? It just feels a bit hacky.

"Is there a certain way to chain methods in PHP?" refers to the safest and easiest to manage way of chaining methods. - This is important to me as when releasing my code I want it to be in the correct community-accepted format.

0

There are 0 best solutions below