Model-View-Controller
While not a comprehensive guide on MVC, this section aims to introduce you to the concept as well as impart a few best practices from the li3 perspective.
The primary goal of a model is to manage domain knowledge for a particular object. Model classes in li3 are typically named after the object they manage. The model is in charge of CRUD operations for the object, data validation, as well as commonly used data manipulation operations upon that object’s data.
- Simple saving and fetching of user data
- Concatenation of the first and last names for a “virtual” full name field
- Complicated finder methods for user data (finding a user by account status or age)
Views present model data and the interface for your application. They contain some logic, but it’s usually pretty light things like conditionally showing information, reusable bits of presentational code, or looping through objects in order to present them.
While most views in li3 contain HTML, MVC programming allows you to switch between presentational technologies easily. A well-built MVC application should be able to show and switch between HTML, PDF, SVG or JSON with minimal effort.
Typical controller functions might include:
- Authenticating a request, and re-routing a user based on permissions
- Handling an error in the application
- Forwarding a user along to a different action based on model state
Controllers are often named after the model they primarily deal with.
- Models should be feature-rich; Controllers should be very thin.
- Views should only contain logic that is presentational in nature. This usually means no access to models.
- Actions dealing primarily with a given model should be placed in that model’s controller.