Welcome Guest, Not a member yet? Register   Sign In
creating new class objects and use them in CI
#1

[eluser]cyrigniter[/eluser]
Hello,

I want to create a class named User, which would contain all information relative to a.. user, given her id in my DB.
The instanciation would be :

Code:
$me = new User($this->session->userdata('id'));

the User class would make calls to the database to fetch useful information (user name, e-mail, etc.).

And from there I'm stuck :
I don't know where to put my User.php class file. I put it in a application/classes folder, and then wanted it to autoload. I created a MY_Controller extending CI_Controller, but with autoload, and changed the extension of my controllers to call MY_Controller instead of CI_Controller, and that would not work. I manually included the class (require_once 'User.php') and then of course, when I make DB calls (with CI syntax) I get errors cause I cannot use my Models in this class because it extends nothing from CI ($this->load gives an error). All this makes sense to me, but I just don't know what to do to get things done. Maybe creating a new model just for that class ? or is there another way to do it ?
#2

[eluser]n0xie[/eluser]
It's a bit of a hack. I don't know why you just wouldn't use the normal model approach, or use an ORM. Anyway this works

Make sure your autoloader has access to User.php
Code:
// User.php
class User {

    protected $user_id;
    
    public function __construct($user_id)
    {
        $this->user_id = (int) $user_id;
        $this->db = get_instance()->db;
    }

    public function get()
    {
        $query = $this->db->where('id', $this->user_id)->limit(1)->get('users');
        return ($query->num_rows() > 0) ? $query->row() : FALSE;

    }
}

// Controller
$user = new User(1);
var_dump($user->get());
#3

[eluser]cyrigniter[/eluser]
cool
get_instance()->db was the key

thanks a lot !




Theme © iAndrew 2016 - Forum software by © MyBB