In Laravel, do I have to create a separate model and controller for each database table/collection?

为君一笑 提交于 2021-01-29 09:40:32

问题


I am developing a little application with PHP web framework Laravel v6 and MongoDB (with jenssegers moloquent) as database engine. This is my first encounter with any MVC framework. I have the following collections in my database:

  1. allPaintingsCollection
  2. paintingHistoriesCollection
  3. paintingCategoriesCollection
  4. artGalleriesCollection
  5. paintingArtistsCollection
  6. supervisorArtistsCollection
  7. smPlatformsCollection
  8. nonSmPlatformsCollection
  9. targetSchoolsCollection

I have been following this tutorial. I have the following two questions:

  1. Do I have to create a separate Model (separate class in a separate file) for each collection above?
  2. Do I have to create a separate Controller (separate class in a separate file) for each collection above?

回答1:


New Answer: 1. Yes, you will need to create a separate model to use the ORM. Ideally, the model should only support a single collection, doing so you can create custom logic. Remember, One Model One Collection/Table.

  1. For Controllers, you can write it any way you like, you can use all models inside a single controller. But what I have learned so far using Laravel, you should create a single controller for each model to fully and logically support the separation of concerns.

Know the BTS:

Laravel heavily uses PHP Composer's autoloader functionality, so having multiple classes in a single file won't work.

For example, when autoloader starts, it would look for User class in \App\Models\User.php file. Having multiple classes in a single file won't help in this case.

Latest Laravel's version follow PSR-4 standard. You can have a look at it for more understanding.

For more PHP coding standards you can have a look at PSR-2 standards.



来源:https://stackoverflow.com/questions/62437927/in-laravel-do-i-have-to-create-a-separate-model-and-controller-for-each-databas

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!