MVC (Model-View-Controller) is a foundational design pattern for creating well-organized and maintainable applications. In this guide, we will walk you through setting up a basic project using MVC architecture with tables and diagrams to simplify the concepts.
Overview of MVC Components
Component | Description |
---|---|
Model | Manages data, logic, and rules of the application. |
View | Responsible for displaying data to the user. |
Controller | Handles user input, updates the Model, and selects the appropriate View. |
Steps to Set Up a Basic MVC Project
1. Folder Structure
Organize your project to separate concerns effectively. Here’s an example structure:
project-folder/
|-- models/
| |-- userModel.js
|-- views/
| |-- userView.ejs
|-- controllers/
| |-- userController.js
|-- routes/
| |-- userRoutes.js
|-- app.js
|-- package.json
Folder/File | Purpose |
models/ | Contains logic to interact with the database. |
views/ | Templates to display data. |
controllers/ | Implements business logic. |
routes/ | Maps routes to controllers. |
app.js | Main entry point for the application. |
package.json | Manages project dependencies. |
2. Install Dependencies
Initialize your project and install necessary dependencies like Express:
npm init -y
npm install express body-parser ejs
3. Implement MVC Components
Model
Create a simple model, for example, userModel.js
:
const users = [];
module.exports = {
addUser: (user) => users.push(user),
getUsers: () => users,
};
View
Create a view template, userView.ejs
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>User List</title>
</head>
<body>
<h1>Users</h1>
<ul>
<% users.forEach(user => { %>
<li><%= user %></li>
<% }); %>
</ul>
</body>
</html>
Controller
Define controller logic in userController.js
:
const userModel = require('../models/userModel');
module.exports = {
addUser: (req, res) => {
const { name } = req.body;
userModel.addUser(name);
res.redirect('/users');
},
getUsers: (req, res) => {
const users = userModel.getUsers();
res.render('userView', { users });
},
};
Routes
Create routes in userRoutes.js
:
const express = require('express');
const router = express.Router();
const userController = require('../controllers/userController');
router.get('/users', userController.getUsers);
router.post('/users', userController.addUser);
module.exports = router;
App Entry Point
Link everything in app.js
:
const express = require('express');
const bodyParser = require('body-parser');
const userRoutes = require('./routes/userRoutes');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
app.use('/', userRoutes);
app.listen(3000, () => console.log('Server running on http://localhost:3000'));
MVC Workflow Diagram
Below is a simplified flowchart of how MVC architecture processes a user request:
graph TD;
User[User Interaction] -->|HTTP Request| Controller;
Controller -->|Fetch/Update Data| Model;
Model -->|Data| Controller;
Controller -->|Render| View;
View -->|HTML Response| User;
Example Workflow
Scenario: A user submits their name through a form, and the application displays the updated user list.
- User Interaction: User submits the form at
/users
. - Controller Processes Input:
addUser
method inuserController.js
adds the name to the Model. - Model Updates Data:
userModel.js
updates theusers
array. - View Displays Data:
userView.ejs
renders the updated list of users. - Response Sent: The updated list is displayed in the browser.
Advantages of This Setup
- Clear Separation of Concerns: Each layer has a distinct responsibility.
- Scalability: Easily extendable with new features.
- Reusability: Models, Views, and Controllers can be reused in different parts of the application.
By following these steps, you can set up a basic project with MVC architecture that is clean, organized, and ready for scaling. Happy coding!