call a helper function in controller in codeigniter

喜夏-厌秋 提交于 2020-01-01 19:21:31

问题


I created a helper for visit hits and it contains a function which inserts some data in to the database:

hits_counter_helper.php :

function count_hits($options = array())
{

    //Determine whether the user agent browsing your site is a web browser, a mobile device, or a robot.
    if ($this->agent->is_browser())
    {
        $agent = $this->agent->browser() . ' ' . $this->agent->version() . ' - ' . $this->agent->platform();
    }
    elseif ($this->agent->is_robot())
    {
        $agent = $this->agent->robot();
    }
    elseif ($this->agent->is_mobile())
    {
        $agent = $this->agent->mobile();
    }
    else
    {
        $agent = 'Unidentified User Agent';
    }

    //Detect if the user is referred from another page
    if ($this->agent->is_referral())
    {
        $referrer = $this->agent->referrer();
    }

    // correcting date time difference by adding 563 to it.
    $date = date('Y-m-j H:i:s', strtotime(date('Y-m-j H:i:s')) + 563);

    $data = array (

        'page_Address'  =>   current_url(),

        'user_IP'       =>   $this->input->ip_address(),

        'user_Agent'    =>   $agent,

        'user_Referrer' =>   $referrer,

        'hit_Date'      =>   $date

    );

    $this->db->insert('counter', $data);

}

once I auto loaded the helper and called this function in my controller as:

My_controller.php:

public function index() {
    count_hits();
    //index code here
}

The problem is that I am getting a blank page and other codes does not run I think. What am I doing wrong?!


回答1:


Add the following code to the beginning of your helper function:

//get main CodeIgniter object
$CI =& get_instance();

Replace all $this with $CI in your function.

and then load the helper function wherever you want in your controller like this:

count_hits();


来源:https://stackoverflow.com/questions/32037705/call-a-helper-function-in-controller-in-codeigniter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!