I am writing a REST wrapper class which looks like:
class RestApi
{
public function __call($method, $resource, $data = []){
return $this->call($method, $resource, $data);
}
public function call($http_verb, $resource, $data = []){}
}
But when I try to run the following...
$ra = new RestApi();
$ra->post('api/book/index');
It throws following error...
RestApi::__call() must take exactly 2 arguments
I want to get rid of duplication code so I have decided to use __call
magic method for all four http verbs. Please suggest a way. Thanks.
Like the error message suggests, the
__call
magic method only takes 2 arguments: the name of the method that was requested, and an array of arguments that were passed. All this info can be found here.With that in mind, maybe modify your code to look more like this:
Assuming you implement the actual API requests with CURL (which may be a very big assumption), you could do something like this inside your
call()
method:This is purely an example to demonstrate the conditional logic you can do with the
__call()
magic method. There are many libraries and frameworks that create REST wrappers like what you're trying to do. I suggest looking at one of those just as a learning experience, or maybe investigate a library like Guzzle.Note: Of course, with an optional second argument (like what you have above), it would be smart to do some checks to see if
$arguments[1]
, etc. exist before blindly passing them along. Otherwise you'll get something likePHP Notice: Undefined offset: 1
.UPDATE
Regarding my last paragraph, @JayTaph had a good suggestion. A concise way to do this (one line, with no extra checks necessary) would be to use the following:
If only one argument gets passed, after the first element gets shifted off with
array_shift()
,$arguments
will be an empty array, which avoids thePHP Notice: Undefined offset
error I mentioned above.