I was pushed into an existing CodeIgniter project and am familiarizing myself with the proper conventions for their MVC approach. One thing I'm stuck on is relating models and controllers. The CI documentation gives almost no guidance on this and I'm not sure what the correct approach is. Our project is an API which is called by external applications so I'm not concerned with views, only models and controllers.
This is an off-the-cuff example rather than a practical example, but hopefully it will help me understand: Let's say that I'm making an application that has minigames and a virtual store. The player can earn points by playing minigames. They can spend those points in the shop to buy items. They can also sell items in the shop to earn points. The application should log each transaction of points.
In this situation, my thinking is I would have a:
- ShopModel - interacts with the database to load product data and to save what items the user has purchased
- MiniGameModel - interacts with the database to load data about the minigames and save scores
PointsModel - interacts with the database to transfer points into or out of the player's account (and writes corresponding log entries in the "log" table)
ShopController - utilizes ShopModel and PointsModel
- MiniGameController - utilizes MiniGameModel and PointsModel
So, for example, the user tells the application they want to search the shop for "weapons". The application requests weapons from the controller. The shop controller builds a query and the shop model executes the query and returns the records. The controller formats the records as JSON and sends them back to the application.
The user tells the application they want to buy the shield. The application notifies the shop controller. The shop controller queries the price from the shop model, then tells the points model to subtract the points, then tells the shop model to give the player the shield. Finally, the controller notifies the application via JSON that the shield was purchased.
Is this an acceptable structure, or should each controller only have one model? If there should only be one model per controller, how do I avoid copy-pasting code that handles the points? Am I doing this completely wrong?
Please do not get hung up on the database structure or anything like that. This is not a real example. I'm just trying to figure out how to organize classes.