staticcode's avatar

How to write Eloquent like functions with ->

Hi guys,

I really love the way Laravel handels a lot off stuff, especially Eloquent. But can someone explain to me how I can make stuff like this on my own? an example:

    $object = new Calculator;
    $outcome = $object->add(15)->subtract(5)->calc();

In this case I have "one" line of code, with multiple calls to functions with the arrows ( -> ). The part that I wonder about is how could I write something like this myself so I can use multiple arrows instead of having to do it like I normally would with my classes:

    $object = new Calculator;
    $object->add(15);
    $object->subtract(5);
    $outcome = $object->calc();

Hope someone can explain this to me on a low level so I can understand it quite well ^^

Best regards

0 likes
2 replies
burlresearch's avatar
Level 40

It's up to you to implement a fluent interface when you write your functions. I'd highly recommend looking into the Laravel/Illuminate source code to see how Taylor makes extensive use of this.

Basically for your Calculator methods, just make sure you return a reference to the class itself, then you can chain these method calls the way you want, as the next call always gets passed a reference to the correct class.

Calculator::add(Integer $addend) {
  $this->sum += $addend;
  return $this; // this allows for the fluent-chaining
}
staticcode's avatar

ahhh thats an awesome tip, with this I can find exactly what I was looking for! thanks burlresearch!

Please or to participate in this conversation.