dtnpzghys01643322
2015-06-24 17:39
浏览 48
已采纳

用于REST HTTP谓词的PHP __call方法

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.

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doubo6658 2015-06-24 17:59
    已采纳

    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:

    public function __call($method, $arguments) {
        return $this->call($method, $arguments[0], $arguments[1]);
    }
    

    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:

    switch (strtoupper($http_verb)) {
        case 'GET':
            // Nothing special happens here, this is CURL's default behavior
            break;
        case 'POST':
            curl_setopt($ch, CURLOPT_POST, true);
            break;
        case 'PUT':
            curl_setopt($ch, CURLOPT_PUT, true);
            break;
    
        // Etc...
    }
    

    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 like PHP 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:

    public function __call($method, $arguments) {
        return this->call($method, array_shift($arguments), $arguments);
    }
    

    If only one argument gets passed, after the first element gets shifted off with array_shift(), $arguments will be an empty array, which avoids the PHP Notice: Undefined offset error I mentioned above.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题