0

I have a philosophic question on CodeIgniter, and the role of its model on the utilisation of "new" to instance something.

It looks to me that the idea, is that you use for example to use let say a model of a book

$this->load->model("book_model")

instead of

new book_model

What I mean, is that since you load only once the book_model, you will have only one instance of a book_model, and if you want to model multiple books, you will use a createNewBook function in the book_model, instead of going through the _construct fonction after using "new".

Is it right to see it like this? I mean to consider that I use the same instance of book_model and a function inside it "initiateBook"? Should we consider to never use "new" in CodeIgniter?

cam
  • 113
  • 1
  • 10

1 Answers1

3

Actually when you call $this->load->model("book_model") the CodeIgniter does the job for you, which means CodeIgniter's Loader class has a method public function model(...) which instantiate the model that you've passed as an argument, for example book_model here.

Taken from model function in Loader class (located in system/core)

if (in_array($name, $this->_ci_models, TRUE))
{
    return;
}

It checks the _ci_models protected array to see if the requested model is already loaded then it returns and if it's not loaded then it loads it, i.e. (the last segment of model method)

$CI->$name = new $model(); // here $model is a variable which has the name of the requsted model
$this->_ci_models[] = $name; // stores the instantiated model name in the _ci_models[] array
return; // then returns

So, you don't need to use new to instantiate it manually and once a model (same applies with other libraries or classes) is loaded then you can access/use it anywhere in your script.

Since CodeIgniter uses the Singleton (an answer on SO about singleton pattern) design pattern so you have only one super global $CI object (one instance of CodeIgniter) available and it carries everything you've loaded or you'll load.

To load the book_model model and then call the initiateBook() method of that model

$this->load->model("book_model"); // book_model loaded/instantiated
$this->book_model->initiateBook(); // initiateBook() function has been called
Community
  • 1
  • 1
The Alpha
  • 143,660
  • 29
  • 287
  • 307
  • Ok; thanks. So how can how do, if I can't do $book = new book, how can i end up having $book variables in my controller from which i can do $book->name; – cam Jul 21 '12 at 23:28
  • Load it `$this->load->model("book_model")` then call the method `$this->book_model->initiateBook()` – The Alpha Jul 21 '12 at 23:38
  • ok, but if I do this, `book1=$this->book_model->initiateBook()` and `book2=$this->book_model->initiateBook()`, are book1 and book2 the same instance i.e if are $book1->name and $book2->name the same? – cam Jul 22 '12 at 00:11