Dan Matthews
Dan Matthews

Reputation: 1245

How can I instantiate multiple instances of the same object in CodeIgniter?

With traditional OOP, I would (or could, rather) create a model / object that represents a User, with properties that reflect that, i.e., name, id, job title, etc.

I could then create a new instance of that object and assign it to a variable, and if I was looping through a result set, I could create an instance for each one. With CodeIgniter, this seems impossible, as doing:

$this->load->model('User');

Instantiates it, and places it for use at $this->user.

Isn't there any way to use models as objects in a more traditional manner? But without hacking the CodeIgniter way of doing things?

I understand that you can assign things to a different object name using $this->load->model('User', 'fubar'), but it's not as dynamic as simply assigning an instance to a variable.


Thanks for the answers guys. I think that I missed a vital part of working the "CodeIgniter Way", but I've just been looking through a contributed library, and the practice of using the same instance (assigned to the CodeIgniter namespace), but clearing the instance variables after each use, seems to be a great way to work that removes my reservations.

Upvotes: 5

Views: 4510

Answers (4)

Brennan Novak
Brennan Novak

Reputation: 148

Yes, what JustAnil and minboost said are correct. However, standard practice for how the majority of CodeIgniter developers write code is with the following syntax

$this->mymodel->mymethod(); 

Upvotes: 0

Anil
Anil

Reputation: 21910

You can still instantiate objects in CodeIgniter the same way as you do it normally.

$user1 = new Users(); // Instantiate
$user2 = new Users();

$user1->property;     // Using it
$user2->method()

unset($user1);        // Unset it when done for good practice.

Upvotes: 0

minboost
minboost

Reputation: 2563

You don't have to use the load() functions. You can just use require_once and new User(), like you normally would.

Using the load() should only be for things you want in the global CodeIgniter namespace. As you can see, it gets polluted really quickly if you try to use it for everything.

Upvotes: 5

mdgrech
mdgrech

Reputation: 955

// User_model.php

public function get_users() {
    $query = $this->db->get('mytable');
    return $query->result();
}

// User_controller.php
public function show_users() {
    $data['users'] = $this->User_model->get_users();
    $this->load->view('show_users', $data);
}

// show_users.php  (view file)
$x = 0;
foreach ($users as $user) {
    $x = $user;
    $x++;
}

Upvotes: -2

Related Questions