{}const=>[]async()letfn</>var
WebBackendBasics

MVC architectural pattern

A detailed explanation of MVC: what it is, why it is needed, how it works. Clear examples and similar patterns. Learn how to get started with MVC, with code for beginners.

К

Kodik

Author

7 min read

If you've ever heard of architectural patterns in programming, then you've probably heard of MVC. 😎 But what is it and why do you need it at all? Let's figure it out together, and I'll try to make it as simple and clear as possible.

/

What is MVC? 🤔

MVC stands for Model-View-Controller (Model-View-Controller). This is an architectural pattern that helps organize your code so that it is easier to develop and maintain.

MVC divides the application into three main components:

  • Model — stores data and the logic of working with them.

  • View — responsible for displaying data to the user.

  • Controller — connects the Model and the View, controls user actions and determines what data to send to the View.

Why do you need MVC? 🤓

The main goal of MVC is to make the code understandable and to share responsibility. For example, if you need to change the logic of working with data, changes are made to Model, and the code responsible for displaying on the screen (View), remains untouched. This simplifies development and makes the code more readable and maintainable.

MVC is often used in web development to separate the user interface from the logic of business processes. This separation allows several developers to work in parallel on the same system: someone deals with the interface, someone with the logic of working with data.

MVC analogues

In addition to MVC, there are other architectural patterns, such as:

  • MVP (Model-View-Presenter): Similar to MVC, but the Controller is replaced Presenter — it works more closely with View.

  • MVVM (Model-View-ViewModel): A pattern often used in desktop and mobile applications, especially with frameworks such as Angular or Vue.

All these patterns have one goal — to divide responsibility between parts of the code to simplify its support.

How does MVC work? 🔍

Let's figure out how the main components of MVC work using a simple example.

Imagine a note-taking app. It allows you to create notes, display them and delete them.

1. Model

The model is responsible for storing and managing data. In our example, this will be a list of notes:

class NoteModel {
  constructor() {
    this.notes = [];
  }

  addNote(note) {
    this.notes.push(note);
  }

  getNotes() {
    return this.notes;
  }

  deleteNote(index) {
    this.notes.splice(index, 1);
  }
}

Here we have a class NoteModel, which allows you to add, delete, and receive notes.

2. View

The view is responsible for displaying data to the user. For example, it will display our notes on the screen:

<div id="app">
  <input type="text" id="noteInput" placeholder="Enter a note...">
  <button onclick="addNote()">Добавить заметку</button>
  <ul id="noteList"></ul>
</div>

View is usually HTML, which displays data and in which the user enters new data.

3. Controller

The controller ties everything together. It accepts input from the user and interacts with the Model to modify or display the data.

const model = new NoteModel();

function addNote() {
  const input = document.getElementById('noteInput');
  const note = input.value;
  if (note) {
    model.addNote(note);
    input.value = '';
    updateView();
  }
}

function updateView() {
  const noteList = document.getElementById('noteList');
  noteList.innerHTML = '';
  model.getNotes().forEach((note, index) => {
    const li = document.createElement('li');
    li.textContent = note;
    li.onclick = () => {
      model.deleteNote(index);
      updateView();
    };
    noteList.appendChild(li);
  });
}

Here Controller manages the interaction between View and Model. When a user adds a note, Controller calls the model methods and updates the view.

MVC in frameworks 📚

Many popular frameworks use the MVC architecture. Let's look at some examples of how MVC is implemented in modern frameworks.

1. Backend: Ruby on Rails

Ruby on Rails is a popular framework for developing the server side of web applications that follows the principles of MVC.

  • Model: In Rails, models are usually associated with a database and manage application data.

  • View: Views are HTML templates that display data to the user.

  • Controller: Controllers receive requests from users, process them using models, and return views.

Example of a controller in Ruby on Rails:

class NotesController < ApplicationController
  def index
    @notes = Note.all
  end

  def create
    @note = Note.new(note_params)
    if @note.save
      redirect_to notes_path
    else
      render :new
    end
  end

  private

  def note_params
    params.require(:note).permit(:content)
  end
end

2. Frontend: Angular

Angular is a framework for developing the client part, which also implements the MVC architecture through MVVM (Model-View-ViewModel), which is similar to MVC.

  • Model: Application data is stored in services or directly in components.

  • View: HTML templates display data.

  • Controller/ViewModel: Components in Angular act as controllers, linking data to the view.

Example of a component in Angular:

import { Component } from '@angular/core';

@Component({
  selector: 'app-notes',
  template: `
    <div>
      <input [(ngModel)]="note" placeholder="Enter a note...">
      <button (click)="addNote()">Add a note</button>
      <ul>
        <li *ngFor="let note of notes; let i = index" (click)="deleteNote(i)">{{ note }}</li>
      </ul>
    </div>
  `
export class NotesComponent {
  note: string = '';
  notes: string[] = [];

  addNote() {
    if (this.note) {
      this.notes.push(this.note);
      this.note = '';
    }
  }

  deleteNote(index: number) {
    this.notes.splice(index, 1);
  }
}

3. Frontend: React

React is a popular library for developing user interfaces that can follow MVC principles with the right code organization.

  • Model: Data can be stored in the state of components or in separate state managers such as Redux.

  • View: React components are a UI that displays data.

  • Controller: The controller can be considered the logic of the components that controls the state and updates the view.

Example of a component in React:

import React, { useState } from 'react';

function NotesApp() {
  const [note, setNote] = useState('');
  const [notes, setNotes] = useState([]);

  const addNote = () => {
    if (note) {
      setNotes([...notes, note]);
      setNote('');
    }
  };

  const deleteNote = (index) => {
    setNotes(notes.filter((_, i) => i !== index));
  };

  return (
    <div>
      <input
        type="text"
        value={note}
        onChange={(e) => setNote(e.target.value)}
        placeholder="Enter a note..."
      />
      <button onClick={addNote}>Добавить заметку</button>
      <ul>
        {notes.map((note, index) => (
          <li key={index} onClick={() => deleteNote(index)}>{note}</li>
        ))}
      </ul>
    </div>
  );
}

export default NotesApp;

4. Backend: Laravel (PHP)

Laravel is a PHP framework that also follows the MVC architecture.

  • Model: Models in Laravel interact with the database and manage the data.

  • View: Views are Blade templates that display data to the user.

  • Controller: Controllers accept user requests, process them, and return the corresponding view.

Example of a controller in Laravel:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Note;

class NotesController extends Controller
{
    public function index()
    {
        $notes = Note::all();
        return view('notes.index', compact('notes'));
    }

    public function store(Request $request)
    {
        $request->validate(['content' => 'required']);
        Note::create($request->all());
        return redirect()->route('notes.index');
    }

    public function destroy(Note $note)
    {
        $note->delete();
        return redirect()->route('notes.index');
    }
}

5. Backend: Django (Python)

Django is a Python framework that uses the MTV (Model-Template-View) approach, similar to MVC.

  • Model: Models in Django manage data and describe the structure of the database.

  • Template (View): Templates are responsible for displaying data to the user.

  • View (Controller): Views accept requests from the user and return the corresponding response.

Example of presentation in Django:

from django.shortcuts import render, redirect
from .models import Note

# View to display the list of notes
def notes_list(request):
    notes = Note.objects.all()
    return render(request, 'notes/notes_list.html', {'notes': notes})

# View to create a new note
def add_note(request):
    if request.method == 'POST':
        content = request.POST.get('content')
        if content:
            Note.objects.create(content=content)
        return redirect('notes_list')
    return render(request, 'notes/add_note.html')

# View to delete a note
def delete_note(request, note_id):
    note = Note.objects.get(id=note_id)
    note.delete()
    return redirect('notes_list')

Advantages of using MVC

  • Simplified development: It is easy to work on individual parts of the application.

  • Increased support: Splitting the application logic into independent parts simplifies making changes.

  • Parallel operation: Several developers can work simultaneously on different parts of the system.

  • Code reuse: Model and view components can be used in other parts of the application, which increases the efficiency of development.

Other frameworks using MVC

  • ASP.NET MVC: Microsoft framework for developing web applications using C#. It clearly separates Model, View and Controller, which makes development transparent and convenient.

  • Django: Python framework using the MTV (Model-Template-View) approach, which is similar to MVC. Model in Django manages data, Template is responsible for the presentation, and View acts as a controller.

  • Laravel: a PHP framework that also follows the MVC architecture. Model manages interaction with the database, View is responsible for the display, and Controller processes user requests.

Conclusion 🎉

MVC is a great way to structure the code, make it cleaner and more maintainable. With its help, you can divide the work on the project between developers and simplify support in the future. Using the example of notes, we saw how easy it is to organize an application by dividing it into Model, View, and Controller.

Try to implement something simple using MVC! This will help you better understand how this pattern works. Good luck with your projects! 🚀

🎯Stop procrastinating

Liked the article?
Time to practice!

In Kodik, you don't just read — you write code immediately. Theory + practice = real skills.

Instant practice
🧠AI explains code
🏆Certificate

No registration • No card