如何从CodeIgniter中的自定义库加载模型以检查数据库中是否存在值?

问题描述 投票:0回答:1

我目前正在使用CodeIgniter中的REST API来根据用户的IP地址显示用户的位置详细信息。问题是,如果用户的IP地址存在,则只从数据库表中检索它。否则,如果用户的IP地址是新的,它将从REST API的响应中调用,并将其保存到数据库表中,以最大限度地减少API调用的数量

我已经尝试使用ipstack API获取结果并在控制器和视图上使用它们。但是,如果会有大量用户,则API请求将受到限制,因为我只使用API​​的免费版本。我还尝试创建一个数据库表,以便插入API检索的值,然后只需选择值以最小化API调用。我还尝试创建一个自定义模型,以便在我创建的API库中调用API,但是当我将模型加载到库时,它给了我错误。

我创建了一个user_location表,以便保存API检索的值,然后显示它们以最小化API调用。 Here is the table that I created in order to save the fetched data being retrieved by the REST 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;
}

}

以下是我得到的错误:

enter image description here enter image description here

php rest codeigniter
1个回答
0
投票

在你的图书馆试试这个

$CI = & get_instance();

$CI->load->model('model_name');
$CI->model_name->method();

https://stackoverflow.com/a/6795969/6573970

© www.soinside.com 2019 - 2024. All rights reserved.