【问题标题】:codeigniter - how to call helper method only in default controller and methodcodeigniter - 如何仅在默认控制器和方法中调用辅助方法
【发布时间】:2018-10-13 14:42:45
【问题描述】:

我创建了一个 helper 用于在 db 中保存 user_agent,它有一个方法 saveVisit();

visit_helper:

  function saveVisit($visitable_type='',$visitable_id='')
  {
    $CI =& get_instance();
    $CI->load->library('user_agent');
    $ip = $CI->input->ip_address();

    $userId = $CI->session->userdata('userId');
    if (!isset($userId)) {
      $userId = 0;
    }
    if ($CI->agent->is_mobile()) {
      $mobile=$CI->agent->mobile();
    }else {
      $mobile=0;
    }
    $data = array(
      'ip'=>$ip,
      'visitable_id'=>$visitable_id,
      'visitable_type'=>$visitable_type,
      'user_id'=>$userId,
      'created_at'=>dbtime(),
      'browser'=>$CI->agent->browser(),
      'version'=>$CI->agent->version(),
      'platform'=>$CI->agent->platform(),
      'mobile'=>$mobile,
      'referral'=>$CI->agent->referrer(),
    );
    $CI->db->insert('visits',$data);
  }

当我调用像 saveVisit(); 这样在我的 helper 中创建的方法时,一切正常,它调用了我写的地方!

但是当我从$route['default_controller'] = 'display/home'; 调用此方法时,此方法将从我所有控制器中的所有方法调用!!!

我只想调用这个方法主页而不是所有控制器/方法!

这个问题只针对我的$route['default_controller'] = 'display/home';

我的控制器代码:

class Display extends CI_Controller {
    public function __construct()
  {
        parent::__construct();
  }
    public function home()
    {
        // some codes here 
        saveVisit('home');
    }
}

我希望saveVisit(); 只在主页而不是其他人调用

已编辑:

我在 helper 中创建了一个新函数来测试并在默认 controller 中调用,该函数被调用一次 BUT 运行 两次!

在帮助程序中测试方法代码:

 function test()
  {
      $CI =& get_instance();

      if ($CI->session->userdata('visit')!=null) {
        $plus = $CI->session->userdata('visit');
        $CI->session->set_userdata('visit',$plus+1);
        echo $CI->session->userdata('visit');
      }else {
        $CI->session->set_userdata('visit',1);
      }

当我在默认 Controller 内部调用 test(); 时,每次页面刷新的结果都是(其他控制器正常):

2
4
6
8
10
12
14
.
.
. 

为什么会这样?

编辑 3:

当我在默认控制器中调用辅助函数时,它将运行两次并从其他控制器运行一次!问题是我没有在其他 controllers 中调用 function

【问题讨论】:

  • 您测试过的不同控制器方法的示例 URL 路径是什么?
  • @codeafin any controller and method like blog/index blog/one product/show and ....
  • 当您访问product/show时,新的test()访问次数是否仍然增加?
  • @codeafin 正如您在我的问题中看到的那样,此问题仅适用于默认控制器而不适用于其他控制器!否 product/show 中未增加两次。在这条路上一切正常
  • 这不是 codeigniter 问题。数以万计的网站在 ci 上运行,没有明显原因的功能运行两次。这是用户错误,但我们没有足够的信息来确定原因。

标签: php codeigniter helper


【解决方案1】:

不要对Display类中的每个函数调用test()函数,而是在__construct()中调用它

<?php

class Display extends CI_Controller {

    public function __construct(){
        parent::__construct();
        test();
    }

    public function home(){
        // some codes here 
        saveVisit('home');

    }
}

【讨论】:

  • 我没有在每个方法中调用test()!我的意思是,test() 运行两次 ~ 并导致 db 中的原始数据重复。无论在哪里打电话test()
猜你喜欢
  • 1970-01-01
  • 2011-08-03
  • 2012-02-13
  • 2011-02-19
  • 2011-02-05
  • 1970-01-01
  • 2021-05-20
  • 2011-02-23
  • 1970-01-01
相关资源
最近更新 更多