【问题标题】:What is the best way to retrieve data from a model that is required on every page in CodeIgniter?从 CodeIgniter 中每个页面所需的模型中检索数据的最佳方法是什么?
【发布时间】:2012-02-21 12:39:51
【问题描述】:

当用户登录到我的 CodeIgniter 应用程序时,我需要一个配置文件列表,他们必须在他们访问的每个页面的菜单中列出这些配置文件。而不是像这样在我的应用程序中的每个方法上调用模型函数:

if ($this->users_model->is_logged_in())
{
    $data->profiles = $this->profiles_model->get_profiles();
}

$this->load->vars($data);

有没有更好的方法来做到这一点?我也考虑过像这样扩展 CI_Controller 类的选项,但无法确定如何最好地将变量传递给需要信息的实际方法。

class MY_Controller extends CI_Controller
{
    public function __construct()
    {
        // Alternatively these could be auto-loaded
        $this->load->model(array('profiles_model', 'users_model'));

        if ($this->users_model->is_logged_in())
        {
            $data->profiles = $this->profiles_model->get_profiles();
        }
    }
}

我关心的是最佳实践、最佳性能和最佳缓存能力(如果可能的话)。

【问题讨论】:

    标签: php mysql codeigniter caching


    【解决方案1】:

    如果我在所有页面上都有我需要的任何内容,我会执行以下操作。

    1. 添加helper
    2. 将您的新助手添加到autoload
    3. 只需在需要的地方调用您的函数。

    我这样做的原因是,如果您需要在许多不同的控制器上使用它,那么将它放在一个易于访问的地方非常方便。当您需要维护代码时,它也会变得容易得多。例如,如果您想添加缓存,则只需将该代码添加到单个函数中,而不必在每个控制器中更改它。

    事实上,在你的具体情况下,我实际上created my own session class 来扩展CI Session。作为一个非常基本的例子(我也使用sessions in database):

    class MY_Session extends CI_Session {
        public function __construct() {
                parent::__construct();
        }
    
        public function login($email, $password) {
            $CI =& get_instance();
            $CI->load->model('usermodel', 'user');
    
            $result = $CI->user->login($email, $password);
    
            if($result === false) {
                return false;
            } else {
                $this->set_userdata('email', $result->email);
    
                return true;
            }
        }
    
        public function is_logged_in() {
            $email = $this->userdata('email');
    
            if(!empty($email)) {
                return true;
            } else {
                return false;
            }
        }
    }
    

    这样,由于您可能将此信息存储在会话中,因此将这些信息放在一起很有意义。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-29
      相关资源
      最近更新 更多