Oritm
Oritm

Reputation: 2121

CodeIgniter: Instances of CI_Model

I was wondering if CI_Model is more like a database layer, or can i really use it like i would normally use a model.

To me it looks really ugly to do things like:

for($i = 0; $i < 3; $i++){
    $this->load->model('user_model', $i);
    $this->user_model->name  = $this->generate_name();
    $this->user_model->age   = $this->generate_age();
}

//... and somewhere else use

for($i = 0; $i < 3; $i++){
    $this->$i->save(); //<-- REALLY UGLY, using the $i
}

Is there another way to store your models, or is a better way to just create a non CI model. That i will end up something like:

$user = new User($this->generate_name(), $this->generate_age());
$this->user_model->saveUser($user);

Let me know..

Upvotes: 0

Views: 179

Answers (1)

minboost
minboost

Reputation: 2563

Don't get caught up with how things are named in CodeIgniter; some things are named in ways that can be confusing to most people.

It sounds to me like you want to implement business logic in your model, and in CodeIgniter it's usually cleaner to do that in a library. Then you can use the the CI_Model classes for the data access layer only.

In your case, it would be: /libraries/User.php <-- the user "model" /models/usermodel.php <-- db operations where user table is the primary table

NOTE: You may find that moving application logic out of controllers and into libraries also makes testing, organizing, and reusing code much easier.

Upvotes: 2

Related Questions