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...
- Should I have one repository for database interactions, or one for each model?
- 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.