如何将模型加载到帮助程序?

ram*_*4nd 20 codeigniter

如何将模型加载到帮助程序?我需要在函数之外加载它,但在函数中使用它们.

Ste*_*ran 45

您可以获得对控制器对象的引用并通过它访问模型.

function my_helper()
{
    // Get a reference to the controller object
    $CI = get_instance();

    // You may need to load the model if it hasn't been pre-loaded
    $CI->load->model('my_model');

    // Call a function of the model
    $CI->my_model->do_something();
}
Run Code Online (Sandbox Code Playgroud)

另一种选择是在调用辅助函数时传递模型.

function my_helper($my_model)
{
    $my_model->do_something();
}

function my_controller_action()
{
    // Call the helper function, passing in the model
    my_helper($this->my_model);
}
Run Code Online (Sandbox Code Playgroud)