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?
Actually when you call
$this->load->model("book_model")theCodeIgniterdoes the job for you, which meansCodeIgniter‘sLoader classhas a methodpublic function model(...)which instantiate the model that you’ve passed as an argument, for examplebook_modelhere.Taken from
model functioninLoader class(located insystem/core)It checks the
_ci_modelsprotected array to see if the requested model is already loaded then itreturnsand if it’s not loaded then it loads it, i.e. (the last segment of model method)So, you don’t need to use
newto 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
CodeIgniteruses the Singleton (an answer on SO about singleton pattern) design pattern so you have only one super global$CIobject (one instance of CodeIgniter) available and it carries everything you’ve loaded or you’ll load.To load the
book_modelmodel and then call theinitiateBook()method of that model