0

我有一个关于 CodeIgniter 的哲学问题,以及它的模型在利用“新”来实例化某些东西方面的​​作用。

在我看来,这个想法是您使用例如使用让我们说一本书的模型

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

代替

new book_model

我的意思是,由于你只加载一次 book_model,你将只有一个 book_model 的实例,如果你想为多本书建模,你将在 book_model 中使用 createNewBook 函数,而不是通过 _construct 函数使用“新”后。

这样看是对的吗?我的意思是考虑我使用相同的 book_model 实例和其中的函数“initiateBook”?我们是否应该考虑永远不要在 CodeIgniter 中使用“new”?

4

1 回答 1

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
于 2012-07-21T21:39:53.130 回答