简体   繁体   中英

Best practice for abstracting database interaction in Laravel 4

I currently have a situation where a user is able to complete a form which can result in the creation of several different models. For example, they post an advert of a car for sale, but in doing so, they needed to create a new brand and also a new model of car (as these did not yet exist in the database).

At the moment, this form is being dealt with in an 'AdvertController'. I now want to abstract my database interaction into a respository. My questions are as follows...

  1. Should I have one repository for database interactions, or one for each model?
  2. If one for each model, which file (controller or repository) should handle the logic which determines whether a new model needs to be created.

In other words, which of the following workflows is best practice (if indeed, either)?

(Assume a database with the following relationships: Advert m-1 CarModel m-1 Brand)

Form completed -> Advert Controller
AdvertController -> tells CarModel repository to create new CarModel model
CarModel_Respository -> creates new CarModel
AdvertController -> sets CarModel relationship with the newly created brand
AdvertController -> tells Brand repository to create new CarModel model
Brand_Respository -> creates new Brand
AdvertController -> tells Advert repository to create new Advert model
Advert_Repository -> creates new Advert
AdvertController -> sets Advert relationship with CarModel
AdvertController -> displays success message

OR... something like this...

Form completed -> AdvertController.
AdvertController -> sends data to DatabaseRepository
DatabaseRepository -> creates new Brand model
DatabaseRepository -> creates new CarModel model
DatabaseRepository -> sets CarModel brand_id as the newly created brand
DatabaseRepository -> creates new Advert model
DatabaseRepository -> sets Advert car_model_id as newly created CarModel
DatabaseRepository -> Sends success message to AdvertController
AdvertController -> sends success message to user.

The great thing about Laravel is the flexiability to do this how YOU want. There is often no "single correct" way to do things - but lots of ways.

Taylor talks about this alot in his book ( From Apprentice to Artisan ), where basically you should determine what option is best for YOU.

Personally, I would go with one repository, which handles all the logic, and interacts with different models on the backend. This is a good seperation of concerns.

It means your controllers only need to know about the single repository, while the repository handles all the backend interactions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM