【问题标题】:How can I load model to helper?如何将模型加载到助手?
【发布时间】:2011-01-29 13:33:01
【问题描述】:

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

【问题讨论】:

    标签: codeigniter


    【解决方案1】:

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

    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();
    }
    

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

    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);
    }
    

    【讨论】:

    • 这很好用,问题是为什么真的需要它。我现在正在使用它,但我确信有更好的方法来实现我正在做的事情。不过谢谢!
    • 效果很好 :) 非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2019-04-02
    • 1970-01-01
    • 1970-01-01
    • 2015-04-29
    • 1970-01-01
    • 2014-10-13
    • 2022-01-20
    • 2011-04-20
    相关资源
    最近更新 更多