0

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.

Jack Hales
  • 1,574
  • 23
  • 51
  • "Is there a certain way?" Yes and no. IMHO, just there's when you can use or not. Take a look there http://stackoverflow.com/questions/17412460/how-to-create-a-fluent-query-interface – Gabriel Heming Jan 03 '17 at 10:38
  • Primarily opinion based, too broad, and already answered. SO Bingo! ;) – yivi Jan 03 '17 at 10:44
  • @yivi Yeah good point, I knew it was a pretty broad question, I just thought it was an interesting topic to do a question about since it's not a thing that's got many different ways to do it. `:-)` – Jack Hales Jan 04 '17 at 11:52

0 Answers0