douzuizhuo0587 2012-03-22 03:39 采纳率: 0%
浏览 50
已采纳

CodeIgniter - Model无法访问CodeIgniter中的全局变量

I'm trying to access global variables from a model. The global variable is set from a controller:

function sets(){
        $value = $this->input->post('current_id');
        $anywhere = array('current_id'=>$value);
        $this->load->vars($anywhere);

}

But the model doesn't know the value of the current id:

$session_id = $this->load->get_var('current_id');
  • 写回答

3条回答 默认 最新

  • doumu8217 2012-03-22 19:03
    关注

    Unfortunately the CodeIgniter Model doesn't have access to the values that you're looking for. But there is hope! There are a few ways to go about having getting access to the parameters that are loaded from the request, choose your poison, but having a defined contract interface for your model is, in my opinion, something that makes writing code easier and less of a hassle to maintain down the line.

    A reference to the CodeIgniter object can be grabbed like so:

    $ci =& get_instance();
    $session_id = $ci->load->get_var('current_id');
    

    Of course this would be the nasty way to go about getting at your data. A better approach would be to pass it in to the model itself as a parameter. You're not going to be paying for much in doing so, and it gives you a contract signature on the method where you can point and say "Hey, this should be the current_id of the model:

    function sets($session_id)
    {
    ...
    }
    

    And, of course, you would just pass in the value you wish $current_id to be as an argument in that function call. This gives you the flexibility of not having to rely on the fact that you're populating the model from a POST HTTP request.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?