Reputation: 91
I'm thinking about creating a class that uses method chaining. What I'm trying to achieve is the type the output of methods, based if the methods are chained or not.
$var = $instance->user($id);
Returns an array with the necessary information.
$var = $instance->user($id)->action($arg);
I want the chained method in front of user()
to just pass the argument $id
to the next method and for it not to output anything. Then the method action()
grabs the $id
and return what's asked.
How can I achieve this?
The reason I want don't want to make user()
return its normal result code is because I intend to use this in an API wrapper. Returning the "normal" user()
will cost me an additional X-Rate-Limit
call. If I could spare this call, and just pass the parameter $id
to the second method, that would be the ideal.
Upvotes: 0
Views: 511
Reputation: 20440
Your current plan is for each of your methods to perform an expensive HTTP call, but you are aware of the potential for significant delay to mount up if several methods are chained.
A good solution for this is to use chained methods to set the parameters and then to run an execute method at the end. So, you might modify your examples thus:
$var = $instance->user($id)->execute();
$var = $instance->user($id)->action($arg)->execute();
You'd have user()
and action()
returning $this
(as well as changing the instance's state in some way) and then execute()
would run the HTTP call in one go. This makes all calls prior to the last one very inexpensive indeed.
The return value could be $this
, although a terminator method of this kind might just return a boolean success value. Your examples imply that a value is expected - having that relate to the last method prior to the execute()
would probably work too.
Upvotes: 1
Reputation: 1902
Instead of returning an array, user() should return a User object.
This way, $var = $instance->user($id);
will return the infos you need (because all the infos will be in the User object) and $var = $instance->user($id)->action($arg);
will call action() on the User object (this way, you can easiely access the id of the user).
No more need to differentiate how user() has been called. ;)
Upvotes: 0