CodeIgniter - Use of "new" to create

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


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?


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))

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

Need Your Help

Replace Rows in Notepad++

regex notepad++

I'd like to convert stuff like this:

Inserting a foreign key. Excel VBA and MS Access 2003

ms-access excel-vba vba excel

I have two tables: Department(Dept_ID,Dept_Name). and table Employee(Empl_ID, Empl_Name,Salary,Dept_ID). The IDs are auto-numbers.