August 17, 2025

Design patterns CQRS, MVC, MVVM, Repository

1. CQRS (Command Query Responsibility Segregation)

Explanation (Simple English):
CQRS is a design pattern that separates write operations (commands) from read operations (queries). This improves performance and makes the system easier to maintain.

Example:

// Command: Add a new user
class CreateUserCommand {
    public $name;
    public function __construct($name) { $this->name = $name; }
}

// Query: Get user list
class GetUsersQuery {}
  • Writing: CreateUserCommandHandler handles adding users
  • Reading: GetUsersQueryHandler handles fetching users

Key point: Read and write are separate, so they don’t affect each other.


2. MVC (Model-View-Controller)

Explanation:
MVC divides an application into three parts:

  • Model → Handles data and business logic
  • View → Handles UI and display
  • Controller → Handles input and connects Model & View

Example (PHP/Laravel):

class UserController {
    public function show($id) {
        $user = User::find($id); // Model
        return view('user', ['user' => $user]); // View
    }
}

Key point: MVC is very common in backend web frameworks.


3. MVVM (Model-View-ViewModel)

Explanation:
MVVM is often used in frontend frameworks like React or Vue.

  • Model → Data
  • View → UI
  • ViewModel → Connects Model & View, handles state and logic

Example (React):

function Counter() {
  const [count, setCount] = useState(0); // ViewModel

  return (
    <div>
      <p>Count: {count}</p>  {/* View */}
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

Key point: MVVM allows UI to automatically update when data changes.


4. Repository Pattern

Explanation:
Repository Pattern is used to separate business logic from data access.

  • Business logic does not know the details of the database
  • Makes the system easier to maintain and test

Example:

class UserRepository {
    public function findById($id) {
        return User::where('id', $id)->first();
    }
}

class UserService {
    private $repo;
    public function __construct(UserRepository $repo) { $this->repo = $repo; }
    public function getUserProfile($id) {
        return $this->repo->findById($id);
    }
}

Key point: Repository abstracts database operations, so your code is more flexible.