PHP __call REST HTTP 动词方法

PHP __call method for REST HTTP Verbs

我正在编写一个 REST 包装器 class,它看起来像:

class RestApi
{
      public function __call($method, $resource, $data = []){
           return $this->call($method, $resource, $data);
      }

      public function call($http_verb, $resource, $data = []){}
}

但是当我尝试运行以下...

$ra = new RestApi();
$ra->post('api/book/index');

它抛出以下错误...

RestApi::__call() must take exactly 2 arguments

我想摆脱重复代码,所以我决定对所有四个 http 动词使用 __call 魔术方法。请提出一个方法。谢谢。

如错误消息所暗示的那样,__call 魔术方法只需要 2 个参数:请求的方法的名称,以及一个 array 的参数通过。所有这些信息都可以在 here.

中找到

考虑到这一点,也许可以将您的代码修改为更像这样:

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

假设您使用 CURL 实现实际的 API 请求(这可能是一个非常大的假设),您可以在 call() 方法中执行类似的操作:

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...
}

这纯粹是一个示例,用于演示您可以使用 __call() 魔术方法执行的条件逻辑。还有很多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.

注意:当然,如果有一个可选的第二个参数(就像上面的那样),在盲目地传递它们之前做一些检查以查看 $arguments[1] 等是否存在是明智的。否则你会得到类似 PHP Notice: Undefined offset: 1.

的东西

更新

关于我的最后一段,@JayTaph 有一个很好的建议。一种简洁的方法(一行,无需额外检查)是使用以下内容:

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

如果只传递一个参数,在第一个元素被array_shift()移出后,$arguments将是一个空数组,这避免了我上面提到的PHP Notice: Undefined offset错误。