phpdatabasecodeignitermodelclass-extensions

Codeigniter autocheck db depending on session value


I'm trying to force my app to check every time it loads a model or controller depending on which is my session value.

This is actually running, but just when I get throw this model.

class News_model extends CI_Model {

public function __construct()
{
    parent::__construct();
    if($this->session->dbname=='db1'){
        $this->db=$this->load->database('db1', TRUE); 
    }       
    else{
        $this->db=$this->load->database('db2', TRUE); 
    }
}
public function get_news($slug = FALSE)
{
        if ($slug === FALSE)
        {
                $query = $this->db->get('news');
                return $query->result_array();
        }

        $query = $this->db->get_where('news', array('slug' => $slug));
        return $query->row_array();
}
}

But I do not war to include that __construct code to all my models or controllers.

I've tried to add on my autoload.php

$autoload['model'] = array('General');

Where my General code is something like this.

class General extends CI_Model {

function __construct()
{
    parent::__construct();
    if($this->session->dbname=='db1'){
        $this->db=$this->load->database('db1', TRUE); 
    }       
    else{
        $this->db=$this->load->database('db2', TRUE); 
    }
}
}   

How can I do it?


Solution

  • You can do it by creating a base model which will be extended by your models that require the database check.

    I have simplified the checking and loading code. A simple ternary determines the string to use and stores it in the variable $dbname. That variable is used to load the database, i.e. $this->load->database($dbname);.

    I don't believe you need the second argument to load::database() which means you don't need to set $this->db explicitly. If I'm wrong, use

    $this->db = $this->load->database($dbname, TRUE);
    

    Below is the "base" model. The prefix of the file name is determined in config.php with the setting $config['subclass_prefix'] = 'MY_'; Adjust your base model's file and class name to match the 'subclass_prefix' you use.

    /application/core/MY_Model.php

    <?php
    class MY_Model extends CI_Model
    {
        public function __construct()
        {
            parent::__construct();
            $dbname = $this->session->dbname == 'db1' ? 'db1' : 'db2';
            $this->load->database($dbname);
        }
    
    }
    

    Use the above to create other models like so...

    class News_model extends MY_Model
    {
        public function get_news($slug = FALSE)
        {
            if ($slug === FALSE)
            {
                $query = $this->db->get('news');
                return $query->result_array();
            }
    
            $query = $this->db->get_where('news', array('slug' => $slug));
            return $query->row_array();
        }
    }