I have search about PHP method chaining and all of the tutorial available on the web use the "return $this" for method chaining.
Is there a magic method or library that can be use to help chaining a class method without writing "return $this" at the end of every method.
Within the language itself there is no way to achieve this without return $this
. Functions and methods that do not specify a return value will return null
in PHP as noted in the documentation here: http://php.net/manual/en/functions.returning-values.php.
As null
is not an object with callable methods, an error will be thrown when the next item in the chain is called upon it.
Your IDE might have some features that makes the repetitive task easier to complete, like using snippets or a regex find-and-replace. But outside of that, the language itself presently requires that you design your class to be used fluently with chaining, or specifically design it not to be.
EDIT 1
I suppose you could conceivably use magic methods to achieve something like this "auto-magically". I would advise against it as it's a poor paradigm, but that doesn't mean you can't make it work.
My thought is that you could us the __call
magic method to wrap your actual methods (http://php.net/manual/en/language.oop5.overloading.php#object.call).
<?php
class Whatever
{
public function __call($method, $parameters)
{
//If you're using PHP 5.6+ (http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list)
$this->$method(...$parameters);
//If using < PHP 5.6
call_user_func_array(array($this, $method), $parameters);
//Always return self
return $this;
}
//Mark methods you want to force chaining on to protected or private to make them inaccessible outside the class, thus forcing the call to go through the __call method
protected function doFunc($first, $second)
{
$this->first = $first;
$this->second = $second;
}
}
So I do think this is a possibility, but again I do personally think that a magic solution, while valid, gives off a significant code smell and that might make it better to just deal with typing return $this
where you intend, by your design, to allow for chaining.