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

[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
#2

[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.
#3

[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?
#4

[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
#5

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

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

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

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

[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! =)
#9

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




Theme © iAndrew 2016 - Forum software by © MyBB