dongyupan4850 2016-02-26 23:12
浏览 46
已采纳

cURL内部路由,新对象或相同

I'm building an app that interacts with an API. I use cURL to get the json data. I'm using Slim and will use cURL inside the routes, to get the requested data of course. But I'm unsure how to go about this. Should I open and close the cURL object inside each route?

I'm trying to create as few routes as possible. So I'm doing checks inside the route to see what it is supposed to do, that way I can use the same route for multiple things inside of creating many routes that do nearly the same thing. But I wont be able to do that for all of them. So this is what I have at the moment.

$app->get("/{region}/{action}/{id}", function($request, $response, $args) use($app) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_URL, "url");
    $result = curl_exec($curl);
    curl_close($curl);

    print_r(json_decode($result));
});

$app->get("/eu/status/{id}", function($request, $response, $args) use($app) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_URL, "url");
    $result = curl_exec($curl);
    curl_close($curl);

    print_r(json_decode($result));
});

But it doesn't look right to create a new curl object every time. Any ideas on how I should structure it instead?

  • 写回答

1条回答 默认 最新

  • douguang9014 2016-02-26 23:58
    关注

    One way to clean it up would be to build a wrapper class around curl.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错