Session 6.1 – MVC Architecture
Module 6: Advanced Technologies | Duration: 1 hr
Learning Objectives
By the end of this session, students will be able to:
- Understand the fundamental concepts of MVC (Model-View-Controller) architecture pattern
- Identify the roles and responsibilities of each MVC component
- Explain the flow of data and control in MVC applications
- Recognize the advantages of using MVC pattern in web development
- Apply MVC principles to design web applications
Introduction to MVC
The Model-View-Controller (MVC) is a software architectural pattern that separates an application into three main logical components: the Model, the View, and the Controller. Each of these components is built to handle specific development aspects of an application.
Key Concept
MVC Pattern promotes the separation of concerns, making applications more maintainable, scalable, and testable. It was originally developed for desktop computing but has been widely adopted for designing web applications.
Model
Manages data and business logic
View
Handles display and presentation
Controller
Manages user input and application flow
MVC Architecture Overview
MVC Architecture Diagram
USER
Interacts with the application
CONTROLLER
Receives input, processes requests
MODEL
Business logic & data
VIEW
Presentation layer
RESPONSE
Displayed to user
The Model Layer
The Model represents the data and the business logic of the application. It is responsible for:
Responsibilities
- Managing application data
- Implementing business rules
- Database operations (CRUD)
- Data validation
- Notifying views of changes
Characteristics
- Independent of user interface
- Reusable across different views
- Contains domain-specific data
- Enforces business constraints
- Handles data persistence
// Example: Simple User Model in JavaScript
class UserModel {
constructor(name, email) {
this.name = name;
this.email = email;
this.id = null;
}
// Save user to database
save() {
// Database logic here
return this;
}
// Validate user data
validate() {
if (!this.name || !this.email) {
throw new Error('Name and email are required');
}
return true;
}
// Static method to find user by ID
static findById(id) {
// Database query logic
return new UserModel('John Doe', 'john@example.com');
}
}
The View Layer
The View is responsible for displaying data to the user. It represents the presentation layer of the application.
Responsibilities
- Rendering UI elements
- Displaying data from Model
- Presenting information to users
- Handling UI templates
- User interface logic
Characteristics
- Contains no business logic
- Passive component
- Multiple views for same data
- Template-based rendering
- Responsive to model changes
// Example: Simple View Template (HTML)
<div class="user-profile">
<h2>User Profile</h2>
<div class="user-info">
<p><strong>Name:</strong> {{ user.name }}</p>
<p><strong>Email:</strong> {{ user.email }}</p>
</div>
<button onclick="editUser()">Edit Profile</button>
</div>
// View rendering function
function renderUserView(userData) {
const template = `
<div class="user-profile">
<h2>${userData.name}</h2>
<p>${userData.email}</p>
</div>
`;
document.getElementById('app').innerHTML = template;
}
The Controller Layer
The Controller acts as an intermediary between Model and View. It processes user input and updates both Model and View accordingly.
Responsibilities
- Handling user requests
- Processing input data
- Updating the Model
- Selecting appropriate View
- Managing application flow
Characteristics
- Mediator between Model and View
- Handles application logic
- Routes requests
- Validates user input
- Coordinates updates
// Example: User Controller in JavaScript
class UserController {
constructor(model, view) {
this.model = model;
this.view = view;
}
// Handle user profile display
showUserProfile(userId) {
try {
const user = UserModel.findById(userId);
this.view.render(user);
} catch (error) {
this.view.showError(error.message);
}
}
// Handle user update
updateUser(userId, userData) {
try {
const user = UserModel.findById(userId);
user.name = userData.name;
user.email = userData.email;
user.validate();
user.save();
this.view.showSuccess('User updated successfully');
} catch (error) {
this.view.showError(error.message);
}
}
// Handle form submission
handleFormSubmit(event) {
event.preventDefault();
const formData = new FormData(event.target);
this.updateUser(formData.get('id'), {
name: formData.get('name'),
email: formData.get('email')
});
}
}
MVC Request-Response Flow
Typical MVC Flow
- User Interaction: User interacts with the View (clicks button, submits form)
- Controller Receives Input: Controller captures the user input/request
- Controller Processes: Controller processes the request and determines what to do
- Model Update: Controller updates the Model if needed (data changes)
- Model Processes: Model performs business logic and data operations
- Controller Selects View: Controller chooses appropriate View to display
- View Retrieves Data: View gets data from Model (or Controller passes it)
- View Renders: View renders the data and displays to user
// Complete MVC Example: Simple Todo Application
// MODEL
class TodoModel {
constructor() {
this.todos = [];
}
addTodo(text) {
const todo = { id: Date.now(), text, completed: false };
this.todos.push(todo);
return todo;
}
getTodos() {
return this.todos;
}
toggleTodo(id) {
const todo = this.todos.find(t => t.id === id);
if (todo) todo.completed = !todo.completed;
}
}
// VIEW
class TodoView {
render(todos) {
const html = todos.map(todo => `
<li class="${todo.completed ? 'completed' : ''}">
${todo.text}
<button onclick="controller.toggle(${todo.id})">Toggle</button>
</li>
`).join('');
document.getElementById('todo-list').innerHTML = html;
}
}
// CONTROLLER
class TodoController {
constructor(model, view) {
this.model = model;
this.view = view;
}
addTodo(text) {
this.model.addTodo(text);
this.updateView();
}
toggle(id) {
this.model.toggleTodo(id);
this.updateView();
}
updateView() {
const todos = this.model.getTodos();
this.view.render(todos);
}
}
// Initialize MVC
const model = new TodoModel();
const view = new TodoView();
const controller = new TodoController(model, view);
Advantages of MVC Architecture
Separation of Concerns
Each component has a distinct responsibility, making the code more organized and maintainable.
Parallel Development
Multiple developers can work simultaneously on Model, View, and Controller components.
Reusability
Models can be reused across different views, and views can display data from different models.
Easy Maintenance
Changes in one component have minimal impact on others, simplifying updates and bug fixes.
Testability
Each component can be tested independently, improving overall code quality.
Multiple Views
Same data can be displayed in different formats (web, mobile, API) using different views.
Scalability
Application can grow and evolve more easily with well-defined component boundaries.
MVC Frameworks and Examples
| Platform | Framework/Technology | Description |
|---|---|---|
| JavaScript | AngularJS, Backbone.js, Ember.js | Client-side MVC frameworks for single-page applications |
| Python | Django, Flask | Server-side web frameworks with MVC-like patterns |
| Ruby | Ruby on Rails | Full-stack web framework following MVC pattern |
| .NET | ASP.NET MVC | Microsoft's MVC framework for web applications |
| PHP | Laravel, CodeIgniter, Symfony | PHP frameworks implementing MVC architecture |
| Java | Spring MVC, Struts | Enterprise-level MVC frameworks |
MVC Variations
- MVP (Model-View-Presenter): Presenter handles all UI logic, View is more passive
- MVVM (Model-View-ViewModel): ViewModel acts as data binder between View and Model
- MVT (Model-View-Template): Used in Django, Template handles presentation
- HMVC (Hierarchical MVC): Multiple MVC triads organized hierarchically
Session Summary
Key Points
- MVC Pattern: Separates application into Model, View, and Controller components
- Model: Manages data, business logic, and enforces rules
- View: Handles presentation and user interface rendering
- Controller: Processes user input and coordinates Model and View
- Benefits: Separation of concerns, reusability, maintainability, and testability
- Flow: User → Controller → Model → Controller → View → User
- Widely Adopted: Used in many modern web frameworks across different languages
Next Session Preview
In the next session, we will explore JavaScript Frameworks, understanding how they implement MVC patterns and facilitate modern web application development.