我目前正在使用CodeIgniter中的REST API来根据用户的IP地址显示用户的位置详细信息。问题是,如果用户的IP地址存在,则只能从数据库表中检索它。否则,如果用户的IP地址是新的,则将从REST API的响应中调用该IP地址并将其保存到数据库表中,以最大程度地减少API调用次数
我已经尝试使用ipstack API来获取结果,并在控制器和视图上使用它们。但是,如果会有大量用户,则API请求将受到限制,因为我只是使用API的免费版本。我还尝试创建一个数据库表,以便插入由API检索的值,然后仅选择这些值以最小化API调用。我还尝试创建一个自定义模型,以便在要由API调用的API库中调用,但是当我将模型加载到库中时,它给了我错误。
我创建了一个user_location
表,以保存API检索的值,并稍后显示它们以最小化API调用。
这是我创建的自定义模型的代码,目的是在数据库中保存和获取API结果:
class Ipstack_model extends CI_Model
{
function __construct()
{
parent::__construct();
}
/*
@Description : Select all the fields from the user_location table
@Author : Aristotle Doria
@Output :
@Created Date: 13-02-2019
*/
function get_user_location($table)
{
$this->db->select("*");
$this->db->from($table);
$query = $this->db->get();
return $query->result();
}
/*
@Description : Insert values from the user_location table
@Author : Aristotle Doria
@Output :
@Created Date : 13-02-2019
*/
function insert_user_location($table, $data)
{
$this->db->insert($table, $data);
}
}
这里是我为使用cURL调用ipstack API而创建的库。我试图调用我在库中创建的模型,以便检查数据库中REST API的值,但是我对此部分有些卡住,并给了我一些错误。:
class Ipstack {
public function __construct()
{
$CI =& get_instance();
}
public function fetch_location($ip_address)
{
$CI->load->model('Ipstack_model');
$this->db->where('user_ip_address', $ip_address);
$query = $this->db->get('user_ip_address');
if($query->num_rows() > 0)
{
$this->db->get_user_location();
}
else
{
//set IP address and API access key
$ip = $_SERVER['REMOTE_ADDR'];
if( ENVIRONMENT == 'local' ) $ip = '112.211.220.109';
$access_key = 'e88d4f685c07d3dae06bd952cd7e3c62';
$curl_url = 'http://api.ipstack.com/'.$ip.'?access_key='.$access_key.'';
//Initialize CURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $curl_url);
//store the data;
$json = curl_exec($ch);
curl_close($ch);
}
//Decode JSON response;
$api_result = json_decode($json, true);
return $api_result;
}
}
这是我遇到的错误:
答案 0 :(得分:0)
在您的媒体库中尝试
$CI = & get_instance();
$CI->load->model('model_name');
$CI->model_name->method();