如何在代码点火器中创建一个全局函数?

时间:2017-01-22 05:02:20

标签: php function rest codeigniter curl

我在我的网站上使用rest api ..因为我必须在每个控制器中多次发出curl请求....

$data = array('id' => '01','user_name' => 'abc');
$data_json = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://abc.xyz.com/1.0/index.php/abc_ctrl/function");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json);
$output = curl_exec($ch);
curl_close($ch);
$output3 = json_decode($output);

每个卷曲的功能都是一样的,就像通过向休息控制器发送帖子数据来进行后期调用..... 我厌倦了每次使用相同的线路...我想在配置文件中创建一个post请求函数或者我不知道在主文件中,它接受参数作为url并发布数据并返回输出...

所以每次我必须在配置中调用该功能,我得到结果......

1 个答案:

答案 0 :(得分:1)

你可以这样做:

public function FunctionName()
  {
    $data = array('id' => '01','user_name' => 'abc');
    $url = "http://abc.xyz.com/1.0/index.php/abc_ctrl/function";
    $result = $this->CurlAPI($data,$url);
  }

  public function CurlAPI($data,$url)
  {
    $data_json = json_encode($data);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json);
    $output = curl_exec($ch);
    curl_close($ch);
    $output3 = json_decode($output);
    return $output3;
  }

<强>更新

您也可以在辅助文件中将此函数编写为:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');


    public function CurlAPI($data,$url)
      {
        $data_json = json_encode($data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json);
        $output = curl_exec($ch);
        curl_close($ch);
        $output3 = json_decode($output);
        return $output3;
      }

将此保存到application / helpers /。我们称之为&#34; new_helper.php&#34;

这可以在您的控制器,模型或视图中(不是更可取)

$this->load->helper('new_helper');

echo CurlAPI($data,$url);