What are the Laravel naming conventions for contro

2020-06-07 03:54发布

问题:

I remember hearing you should name your controllers, models and views in a special way. Either singular or plural. I don't remember which ones to name what though, and i can't find anything about it in the doc.

I'm guessing it's like this:

  • Controllers are plural
  • Views are plural
  • Models are singular

Am i on the right track?

I understand it's just a convention and you don't have to follow them, but i still want to know what the right way is.

回答1:

In ASP.NET MVC, I use the convention you mentioned above, expect for Views, which are mixed. If I have a view that displays multiple "things", such as a list of Employees, it is plural. If I have a view that displays a single Employee, it is singular.



回答2:

The convention is:

  • Model class names are singular (class Photo extends model)
  • table names are plural (select id from photos)
  • controller resource names are singular (PhotoController.php)

I couldn't find the convention for controller names defined in the documentation, but all documented examples place the controller resource name in the singular.

From the Laravel 5.5 documentation :

By convention, the "snake case", plural name of the class will be used as the table name unless another name is explicitly specified... Eloquent will assume the Flight model stores records in the flights table



回答3:

It doesn't matter what you name them actually. It's just a matter of taste as long as you do it consistently. Sometimes you won't even have an option but to follow an already determined code style by a current project.

One good practice is that if you can, is to follow the PHP Framework Interop Group standards. Read more on them on their page to find out more.

Laravel 4 will follow all of the standards (PSR-0, PSR-1 and PSR-2), but Laravel 3 isn't. For example: it doesn't use camel case for methods which is "required" by PSR-1.



回答4:

The answers here are pretty correct but if you are talking about Laravel, you should name your Models class in the singular form because of Laravel built in features for instance the Eloquent class is clever enough that it can detect the plurals for the English language. So if our object is singular it will use the plural form of that name to access the database table for that object.