在codeigniter中的控制器中调用帮助函数 [英] call a helper function in controller in codeigniter

查看:63
本文介绍了在codeigniter中的控制器中调用帮助函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为访问量创建了一个帮助器,它包含一个将一些数据插入数据库的功能:

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?!

推荐答案

在辅助函数的开头添加以下代码:

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

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

将所有 $ this 替换为 $ CI

然后在控制器中的任意位置加载辅助函数,如下所示:

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

count_hits();

这篇关于在codeigniter中的控制器中调用帮助函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆