CodeIgniter Forums

Full Version: Independent database
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

[eluser]Diego Pessoa[/eluser]
Hi, I'm trying to use the CI follow the OOP paradigm, but, a thing is incommode me, the database is attached in the CI Model class, specifically, to use the database:

Code:
$this->db->get('table')
or $this->db->select, $this->db->insert, etc.

Follow the OOP rules in a class I need of static methods, example:

Code:
class User extends Model{
public $id;
public $name;
public $login;
public $pass;

public static function getUserById($id) {
$this->db->select('select from users where id = '$id'); //THE PROBLEM
}

}

How I can to use the database in static methods with CI?

Thankx,
Diego Pessoa

El Forum

[eluser]wiredesignz[/eluser]
Unfortunately the database object (db) is attached to the Controller with a reference available to your Model, so I can't see how static mehod calls are possible.

El Forum

[eluser]Diego Pessoa[/eluser]
In my opinion the database access should be independent, I don't like of this attach.

Independent:

Code:
$db = new DB(parameters);
$db->query(
$db->result(
etc


Exists a way to make this with CI?

El Forum

[eluser]wiredesignz[/eluser]
Yes, you can load the database object into your own variable.
Code:
$db = $this->load->database($params, TRUE);  

// $params = DSN string or name of config/database.php settings array

El Forum

[eluser]Seppo[/eluser]
Or you can use...

Code:
$CI =& get_instance();
$CI->db->select('...'); // ...

El Forum

[eluser]wiredesignz[/eluser]
$CI is the controller, so it is no different to using $this.

El Forum

[eluser]Seppo[/eluser]
I meant inside User::getUserById static method.

El Forum

[eluser]Diego Pessoa[/eluser]
Wow! Finally I found the soluction! =) Thanks a lot!!!!

Now:
Code:
public static function getUsers() {
        $users = array();
        $CI =& get_instance();
        $res = $CI->db->get('users');
        foreach($res->result() as $data)
            $users[] = new User($data->id);
        return $users;
    }

Well, it hasn't a good looking, but works! hehe! =)

El Forum

[eluser]wiredesignz[/eluser]
One question on this topic:
Which rule states that you must use static method calls from within a class?

I can see this is a practical issue where class methods are not in object context, but I don't see any difference in accessing the $CI instance (which brings you into object context) and using $this inside a Model, which is already in object context.