Real objects and MVC

穿精又带淫゛_ 提交于 2019-12-13 03:18:53

问题


Until there, I always coded object this way :

// initialization
$husband = new User('Bob');
$wife = new User('Sarah');

// action
$husband->dance();
$wife->read();

// get
echo "The husband is ".$husband->getAge()." years old";

But with CodeIgniter (and MVC), it seems it's better to think this way :

// load model
$this->load->model('user');

// action
$this->user->dance('Bob');
$this->user->read('Sarah');

// get
echo $this->user->getAge('Bob');

But in this case, how to deal with "real objects" ? For example the object "Bob" and the object "Sarah" ? Maybe i'm missing something but it seems for me that Model (second example) != Object (first example). Do this conception of objects are incompatibles ?

I have the directory view, the directory controller, and the directory model. Should I have also a "objects" directory ?


回答1:


If you still want to use CI, you can do this:

// load the class. I think there was a second parameter to avoid instantiation, not sure though. Either way, this will at least load the class
$this->load->model('user',false);

$husband = new User('Bob');
$wife = new User('Sarah');

// action
$husband->dance();
$wife->read();

This is still MVC. The ugly class loading part is there because CI does not have class autoloading on referenciation, so you have to do it manually. Maybe you can integrate a Universal Class Loader somehow.




回答2:


Codeigniter is based around the Singleton Pattern.

In software engineering, the singleton pattern is a design pattern used to implement the mathematical concept of a singleton, by restricting the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects.



来源:https://stackoverflow.com/questions/8069903/real-objects-and-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!