问题
Can somebody perhaps explain here why on earth CakePHP has a convention of using plural names for db tables and controllers and singular for models? Why not always use singular terms, or always plural? For me it seems confusing to always have to think "now do I use plural or singular here?" (Or is there an easy way to remember??) And then you have the join-tables that use a combination of both!
I assume there's a good reason somewhere, but just have not come across it.
(I really hope it's not just because Ruby-on-Rails works that way.)
Simon.
回答1:
CakePHP Conventions
CakePHP’s conventions have been distilled out of years of web development experience and best practices. While we suggest you use these conventions while developing with CakePHP, we should mention that many of these tenets are easily overridden – something that is especially handy when working with legacy systems.
I think the idea is to make it more fluent to read and to think of elements in the right way. Database tables are always plural, because they hold many records. The model is singular, because you should think about finding a single record with it. A select field for model_id
will automatically get its options from $models
, because you select one of many.
$model = $this->Model->find('first'); // reads like English
$model = $this->Models->find('first'); // slightly trips you up
$models = $this->Model->find('all'); // works okay
$models = $this->Models->find('all'); // more logical, but "this models" still trips
It's not always perfect, but I think it's quite a nice convention once you get used to it. I can see how it can be confusing in the beginning though.
回答2:
is there an easy way to remember?
Yes, with respect to the parts where naming convention counts (db/model/controller)... If it's not the name of a model (ie. User
) or the name of a foreign key (ie. user_id
), then it is plural. Everything is basically plural apart from those two things.
来源:https://stackoverflow.com/questions/1752668/why-does-cakephp-use-different-plural-singular-naming-conventions