问题
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