Welcome Guest, Not a member yet? Register   Sign In
Independent database

[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:

or $this->db->select, $this->db->insert, etc.

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

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?

Diego Pessoa

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.

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


$db = new DB(parameters);

Exists a way to make this with CI?

Yes, you can load the database object into your own variable.
$db = $this->load->database($params, TRUE);  

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

Or you can use...

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

$CI is the controller, so it is no different to using $this.

I meant inside User::getUserById static method.

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

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! =)

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.

Theme © iAndrew 2016 - Forum software by © MyBB