How can I create multiple instances of the same object in Codeigniter?

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

Then I could create a new instance of this object and assign it to a variable, and if I iterate over the result set, I could create an instance for each of them. With codeigniter, this seems impossible, because:

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

Creates it and puts it for use in $this->user .

Is there no way to use models as objects in a more traditional way ?, but without breaking into the CI way to do something?

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

Any understanding of this issue is much appreciated by the guys.

EDIT: thanks for the answers guys, I think I skipped the vital part of working on the β€œCodigniter Way”, but I just looked through the library and practice 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.

Once again - thanks for the help and answers.

+6
source share
4 answers

You do not need to use load() functions. You can simply use require_once and new User() as usual.

Using load() should only be done for the objects you want to use in the global CI namespace. As you can see, it gets dirty very quickly if you try to use it for everything.

+5
source

You can still create objects in codeigniter the same way you do it.

 $user1 = new Users(); // Instantiate $user2 = new Users(); $user1->property; // Using it $user2->method() unset($user1); // Unset it when done for good practice. 
0
source

Yes, JustAnil and minboost say, however, the standard practice of how most CI developers write code has the following syntax

 $this->mymodel->mymethod(); 

Do you find a specific problem or problem when you try to write like this? Or is it just different from the style you're used to writing? Please tell us about a use case, where "it is not as dynamic as just assigning an instance to a variable" :)

0
source
 // 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++; } 
-1
source

Source: https://habr.com/ru/post/903134/


All Articles