问题
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:
- allPaintingsCollection
- paintingHistoriesCollection
- paintingCategoriesCollection
- artGalleriesCollection
- paintingArtistsCollection
- supervisorArtistsCollection
- smPlatformsCollection
- nonSmPlatformsCollection
- targetSchoolsCollection
I have been following this tutorial. I have the following two questions:
- Do I have to create a separate Model (separate class in a separate file) for each collection above?
- 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.
- 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