In an MVC perspective, where in the file system should the very basic entities go?
I'm speaking mainly of开发者_运维问答 simple classes that act as containers of data for the controllers and models. Say I have a basket model which takes care of adding fruit and vegetables for the controller. However, during the page load, i.e. between values are accessed from DB or session and are written back again, I am in need to create classes for storing data about fruit and vegetables. Each can contain its quantity or whatnot and perform the most basic of tasks (eventually it may expand but now its stuff like $fruits->add('apple',1)
).
Where should such classes ideally go in the hierarchy of the file system? They should be closely attached to the model, as they won't be needed for anything elsewhere.. Or should they be refractured into something else?
Your $fruits is technically a model as well. I don't know if I agree with being able to ->add through the container (record) object. But they are still models so they can go in the directory or maybe a sub-directory. You can do something like:
models/
controllers/
views/
<object-name>/
lib/
lib can hold other libraries and general classes including base model/controller/view classes. Check out the popular MVC packages to see how they do it as well.
I think you are talking about a data mapper which encapsulates the database logic instead of putting the said logic into the model. This way the only persistence logic inside the model is the coupling to the mapper.
http://martinfowler.com/eaaCatalog/dataMapper.html
These mappers can be put into a subdirectory named Mapper in the same directory where the models reside in:
Model/ Fruit.php Mapper/ Fruit.php
Service layer
In some cases, if you're in need of more flexibility, it might be advisable to introduce a service layer with which you can decouple your models from the mappers so only the mapper knows about the model, or possibly even so that only the service layer knows how the model and the mapper fit together:
http://martinfowler.com/eaaCatalog/serviceLayer.html
(Don't be startled about the talk about "Zend Framework" with the following link since it really makes a lot of good, generic points about architecture and mostly just rants about what ZendFW got wrong)
http://www.angryobjects.com/2009/03/30/writing-robust-php-backends-with-zend-framework/
I'd put these service layers in the filesystem in the same directory level as the models:
Model/ Fruit.php Service/ Fruit.php
ORM Framework
There's also the possibility of using an already existing object relational mapper like Doctrine.
http://www.doctrine-project.org/
Basically you should keep all database logic in models, at least that's the point of MVC.
If you really don't want those methods attached to models, you should create helper classes ( Helper_Fruits ? - /helper/fruits.php I guess ).
精彩评论