Let's say you have three models, Organization, OrganizationUser, and User.
You need to handle the following reqs:
When a user creates an organization, they should become a user associated with that organization (a row in
OrganizationUsertable).If any of the operations above fail, the entire "flow" should fail. This should be implemented with a transaction.
Here are the three best ways I think you can architect it:
- In the controller, create TXN, pass it to the Organization and OrganizationUser models to create their respective rows. Rollback if needed. Controller contains the business logic (has user paid, what type of org... etc).
- In the controller, call
CreateOrganizationServicewhich handles the transaction creation, abstracting it away from the controller; passes it into the models.CreateOrganizationServiceis where we'll keep most of the business logic - Have
Organizationmodel requireOrganizationUsermodel and take care of the transaction creation, the business logic, and creation of theOrganizationUserrow.
Is there a better way of thinking about this, or different approaches/patterns I can apply?