2011-04-09 48 views

回答

1

如果你的網站有一個API,然後把合適的地方是在你的應用程序/文件夾的控制器控制一些,這就是你如何從外部API調用響應。 例子:

 
class Api extends CI_Controller 
{ 
    //Your code goes here 
} 

如果你想使用你想從反應的另一個API,好的做法是創建應用程序/庫/ Some_Api.php類將處理請求和響應外界API,當然你需要在控制器,模型等的某個地方調用它,這取決於你的需求。

編輯 示例這將是:

 
class Myapi extends CI_Controller 
{ 
    public function __construct() 
    { 
     parent::__construct(); 
    } 

    //Here goes your function: 
    public function api_call() 
    { 
     //Some params that Some_Api class will need (if needed of course) 
     $params = array('url' => 'https://checkout.google.com', 'username' => 'your_username'); 

     //Include the library 
     require_once(APPPATH.'libraries/Some_Api.php'); 

     //Create instance of it 
     $api = new Some_Api($params); 

     //Call the external API and collect the response. 
     //In most cases the response is XML and you need to process it as you need it. 
     $response = $api->call_some_api_method(); 

     //Process the response here. 
     //Save to database/file, send emails, do whatever you need to. 
    } 
} 

請注意,我已經使用了一些簡單的例子只是爲了說明如何在過程通常會。大部分工作應該在Some_Api類中完成。 我希望這對你有幫助!

+0

感謝您的幫助。我有另一個問題。如何從我的控制器中調用application/libraries/Some_Api.php中的API函數?謝謝! – user634850 2011-04-09 20:12:53

+0

我編輯了我的答案! – zokibtmkd 2011-04-09 20:52:09

0

我一直有一個關於這個問題爲好。我會告訴你我的方法,並且我渴望得到反饋。當包括別人的API我在模型

例如

class Model extends CI_Model{ 

. 
. 
. 

    function writeLocally{ 

    //do some stuff 


    $this->apiWrite(); 
    } 

    private function apiWrite{ 

    //api write to 3rd party 
    } 


} 

我猜測這是不是基於上述答案的最佳途徑,但反正這是我的兩分錢包括它。

相關問題