How and Where to put an API in Codeigniter folder?
How a开发者_Go百科nd Where to put an API in Codeigniter folder?
and how to call API with Codeigniter?
thanks!
If your site has an API, then suitable place to put is some controller in your application/controllers folder, that's how you can respond to the API calls from outside. Example:
class Api extends CI_Controller { //Your code goes here }
If you want to use another API that you want to get responses from, good practice would be to create class in application/libraries/Some_Api.php that will handle the requests and responses to the outside API, of course you will need to call it somewhere in your controllers, models, etc... depending on your needs.
EDIT Example for this would be:
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. } }
Please note that I have used some trivial examples just to explain how the process usually goes. Most of the work should be done in the Some_Api class. I hope this helps for you!
I have always had a question about this as well. I will tell you my approach and I am eager to get feedback. When including someone else's API I have included it in the model
For example
class Model extends CI_Model{
.
.
.
function writeLocally{
//do some stuff
$this->apiWrite();
}
private function apiWrite{
//api write to 3rd party
}
}
I am guessing this isn't the best approach based on answer above, but anyways that is my two cents.
精彩评论