Laravel 5 Naming Conventions

2019-03-18 12:59发布

问题:

I am bit confused with Laravel conventions as I am new to this framework. I am following Jeffrey Way Laracasts videos he uses Plural for Controller names.

E.g.: PagesController, Cards Controller, PostsController

But if I refer official documentations of Laravel > Controllers and Laravel > Tutorials > Quick Start > Intermediate Task List it uses Singular names.

E.g.: PhotoController, TaskController

Can anybody please list down the official coding conventions for following entities?

Tables: posts, comments, post_comments or Post, Comment, PostComment

Columns: id, post_id, comment_id or id, postId, commentId

Controllers: PagesController, Cards Controller, PostsController or PhotoController, TaskController

Models: Pages, Cards, Posts or Page, Card, Post

回答1:

Tables: posts, comments, comment_post

Columns: id, post_id, comment_id

Controllers: PhotoController, TaskController

Models: Page, Card, Post

For more details check out my Laravel naming conventions table.



回答2:

Remember that "conventions" are just conventions and you could do whatever you want just be constant, however it's better follow the documentation:

  1. Table name: plural and _ to separate words (users, tags, ...)
  2. Columns name: singular and _ to separate words (user, tag, ...)
  3. Models: singular with first letter capitalized and capitalization to separate words (User, Tag, ...)
  4. Controllers: singular with capitalized first letter and capitalization to separate words followed by "Controller" (UserController, TagController, ...)


回答3:

I know I'm from old school (coding since 1984 on computers, though having evolved with PHP and js/ECMAScript since their first version), but the good old Merise rule "never use plural" had strong and good resasons to be respected. What a pity Eloquent forces us to use table name in plural.

PSR-2 or PSR-1 doesn't indicate anything about plural or singular, but for simplicity sake, I heavily recommend to always use singular, excepte where the "system" needs it (as Eloquent does). In that case, don't mix plural and singular. On the datatables used by laravel, we use table names in plural. That's a singularity (compared to the other developments already made or with which we communicate), but all the tables are in plural on that part.

And NEVER make a typo when naming something (example: 'personnal' i.o. 'personal', etc.). Doublecheck first. Orthograph rules.