Paramclasses Academy - Blog

Tutorials Details

←
Post 14 of 15
→

PHP MVC Architecture and Composer Basics

PHP MVC Architecture and Composer Basics

October 16, 2026

PHP MVC Architecture and Composer Basics: Complete Tutorial with Examples

PHP is widely used to build dynamic websites and web applications. As applications grow, writing all PHP code in a single file can make projects difficult to maintain, test, and extend.

Two important concepts that help developers organize PHP projects are MVC architecture and Composer.

MVC separates an application into Model, View, and Controller components. Composer manages PHP packages and their dependencies, making it easier to use third-party libraries and autoload classes.

In this tutorial, you will learn how PHP MVC architecture works, how to create a basic MVC structure, and how to use Composer in a PHP project.

What Is MVC Architecture in PHP?

MVC stands for Model-View-Controller. It is a software design pattern that separates an application's data logic, presentation, and request-handling responsibilities.

The three main components are:

  • Model: Handles application data and business logic, often including database operations.

  • View: Displays information to the user, usually through HTML templates.

  • Controller: Receives requests, coordinates the application logic, and selects the response.

MVC helps developers organize code into separate responsibilities instead of mixing database queries, HTML, and request-handling code in one file.

1. Understanding the Three Components of MVC

<text weight="medium" size="md">Model</text>

The Model is responsible for managing application data and related business rules. For example, a student model may retrieve student records from a database.

<text weight="medium" size="md">View</text>

The View displays data to the user. It typically contains HTML with limited presentation logic.

<text weight="medium" size="md">Controller</text>

The Controller handles an incoming request, communicates with the Model when needed, and passes data to the View.

How MVC Works

<box border radius="lg" padding={3} gap={2}> <box background="surface-secondary" radius="md" padding={3} align="center"> **User / Browser**

<text color="secondary" size="sm">Sends an HTTP request</text>

</box> <box align="center"> <icon name="arrow-down" size="xl" /> </box> <box background="rgba(59,130,246,0.12)" radius="md" padding={3} align="center"> **Controller**

<text size="sm">Handles the request and coordinates the response</text>

</box> <box align="center"> <icon name="arrow-down-up" size="xl" /> <text color="secondary" size="xs">Communicates with the Model</text> </box> <box background="rgba(16,185,129,0.12)" radius="md" padding={3} align="center"> **Model**

<text size="sm">Handles data and business rules</text>

</box> <box align="center"> <icon name="arrow-down" size="xl" /> </box> <box background="rgba(168,85,247,0.12)" radius="md" padding={3} align="center"> **View**

<text size="sm">Renders the response for the user</text>

</box> </box>

This is a simplified illustration. In real applications, the Controller typically passes data to the View, and the View generates the HTML response. The Model does not always communicate directly with the View.

2. Recommended PHP MVC Project Structure

A simple PHP MVC application may use the following directory structure:

php-mvc-project/
│
├── app/
│   ├── Controllers/
│   │   └── StudentController.php
│   │
│   ├── Models/
│   │   └── Student.php
│   │
│   └── Views/
│       └── students/
│           └── index.php
│
├── public/
│   └── index.php
│
├── vendor/
├── composer.json
└── composer.lock

Folder responsibilities:

  • app/Controllers/ contains controller classes.

  • app/Models/ contains models and data-related logic.

  • app/Views/ contains presentation templates.

  • public/ contains the public entry point and publicly accessible assets.

  • vendor/ contains Composer-managed dependencies and generated autoload files.

  • composer.json defines project dependencies and configuration.

  • composer.lock records the resolved dependency versions for reproducible installs.

The vendor/ directory is generated by Composer and should generally not be edited manually.

3. Create a Basic PHP MVC Example

Let's create a small student listing example using plain PHP. This demonstrates the core MVC idea without requiring a framework or database.

Step 1: Create the Model

File path: app/Models/Student.php

<?php

namespace App\Models;

class Student
{
    public function getAll(): array
    {
        return [
            [
                'id' => 1,
                'name' => 'Rahul',
                'course' => 'PHP Development',
            ],
            [
                'id' => 2,
                'name' => 'Priya',
                'course' => 'Web Development',
            ],
        ];
    }
}

The Student model returns sample student data. In a database-driven application, this method could retrieve records through PDO or another database layer.

Step 2: Create the Controller

File path: app/Controllers/StudentController.php

<?php

namespace App\Controllers;

use App\Models\Student;

class StudentController
{
    public function index(): void
    {
        $studentModel = new Student();

        $students = $studentModel->getAll();

        require __DIR__ . '/../Views/students/index.php';
    }
}

The controller calls the Model to retrieve student data and then loads the View.

Step 3: Create the View

File path: app/Views/students/index.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Student List</title>
</head>
<body>
    <h1>Student List</h1>

    <table border="1" cellpadding="10">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Course</th>
            </tr>
        </thead>

        <tbody>
            <?php foreach ($students as $student): ?>
                <tr>
                    <td>
                        <?= (int) $student['id'] ?>
                    </td>
                    <td>
                        <?= htmlspecialchars(
                            $student['name'],
                            ENT_QUOTES,
                            'UTF-8'
                        ) ?>
                    </td>
                    <td>
                        <?= htmlspecialchars(
                            $student['course'],
                            ENT_QUOTES,
                            'UTF-8'
                        ) ?>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</body>
</html>

The View displays the data and escapes text before rendering it in HTML.

Step 4: Create the Public Entry Point

File path: public/index.php

<?php

require dirname(__DIR__) . '/vendor/autoload.php';

use App\Controllers\StudentController;

$controller = new StudentController();

$controller->index();

This example assumes Composer's autoloader has been configured for the App\\ namespace, as explained in the Composer section below. This simple entry point calls the Controller directly; a production MVC application would normally use routing, request handling, and additional security controls.

What Is Composer in PHP?

Composer is a dependency manager for PHP. It helps developers install, update, and manage external libraries and packages used by their applications.

For example, a PHP project might use Composer to install:

  • An email library.

  • A PDF generation package.

  • A payment integration SDK.

  • A logging library.

  • A testing framework.

Composer also provides autoloading, which allows PHP classes to be loaded without manually including every class file.

4. Check Whether Composer Is Installed

Open your terminal or command prompt and run:

composer --version

If Composer is installed correctly, the terminal displays its version.

If the command is not recognized, install Composer using the official installation instructions at getcomposer.org.

After installation, reopen the terminal and run the command again.

5. Initialize Composer in a PHP Project

Open the root directory of your project and run:

composer init

Composer guides you through creating a composer.json file.

Alternatively, you can create a basic composer.json manually:

{
    "name": "example/php-mvc-project",
    "description": "A simple PHP MVC project",
    "type": "project",
    "require": {
        "php": "^8.2"
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/"
        }
    }
}

This configuration declares PHP as a requirement and maps the App\\ namespace to the app/ directory using PSR-4 autoloading.

The PHP version constraint is only an example. Choose a supported PHP version that matches your deployment environment and project requirements.

Run:

composer install

Composer installs the required dependencies and generates the autoload files in vendor/.

6. Configure Autoloading with Composer

Autoloading allows PHP classes to be loaded automatically when they are referenced.

Without autoloading, developers often need to write multiple require or include statements.

For example:

require 'app/Models/Student.php';
require 'app/Controllers/StudentController.php';

With Composer's PSR-4 autoloading, the application can load these classes using their namespaces.

After adding or changing the autoload configuration in composer.json, run:

composer dump-autoload

Now a class declared in app/Models/Student.php with the namespace App\Models can be referenced as:

use App\Models\Student;

$student = new Student();

Composer resolves the class through its generated autoloader.

7. Install a PHP Package with Composer

Suppose you want to use a third-party package in your application.

The general command is:

composer require vendor/package

Replace vendor/package with the actual package name from its official documentation or Packagist.

For example, to install the widely used Guzzle HTTP client:

composer require guzzlehttp/guzzle

Composer adds the dependency to composer.json, updates composer.lock, and installs the package.

You can then use the package according to its documentation.

Important: Review a package's maintenance status, dependencies, license, and security advisories before using it in a production application.

8. Understanding composer.json and composer.lock

These two files serve different purposes.

File Purpose
composer.json Declares dependency requirements and project configuration
composer.lock Records the exact resolved versions of installed dependencies

When working on an existing project, developers usually run:

composer install

This installs the versions recorded in composer.lock, when the lock file is present and valid.

To update dependencies within the constraints declared in composer.json, run:

composer update

This may change dependency versions and the lock file. Review and test updates before deploying them.

9. MVC Architecture vs. Composer

MVC and Composer solve different problems.

Feature MVC Architecture Composer
Main purpose Organizes application responsibilities Manages PHP dependencies and autoloading
Main concepts Model, View, Controller Packages, dependency constraints, autoloading
Helps with Code structure and maintainability Package installation and class loading
Required for every PHP project? No No, but useful for many modern projects
Common usage Organizing application code Installing libraries and managing dependencies

You can use MVC without Composer, and you can use Composer without implementing MVC. Many professional PHP applications use both.

10. PHP MVC and Composer Best Practices

Follow these practices when creating a PHP application:

  • Keep database and business logic out of View templates.

  • Keep Controllers focused on handling requests and coordinating responses.

  • Use prepared statements when working with SQL queries.

  • Escape untrusted data before rendering it in HTML.

  • Use Composer's PSR-4 autoloading instead of manually including many class files.

  • Keep composer.lock in version control for application projects.

  • Do not expose the vendor/ directory or configuration files unnecessarily.

  • Configure the web server's document root to point to public/ where appropriate.

  • Validate requests and implement authentication and authorization where needed.

  • Use a PHP framework when its routing, validation, database, and security features will benefit the project.

Frequently Asked Questions (FAQs)

1. What is MVC in PHP?

MVC is a design pattern that separates application responsibilities into Model, View, and Controller components.

2. What is Composer used for in PHP?

Composer manages external PHP packages, resolves dependencies, and provides autoloading support.

3. Is Composer required for PHP?

No. Basic PHP programs can run without Composer, but Composer is very useful for modern projects that use external libraries or autoloading.

4. What is the difference between composer install and composer update?

composer install uses the versions recorded in composer.lock when available. composer update resolves dependencies again within the declared constraints and updates the lock file.

5. Can MVC be used without a PHP framework?

Yes. You can implement a basic MVC structure in plain PHP. Frameworks such as CodeIgniter and Laravel provide additional tools and conventions for building applications.

6. What is PSR-4 autoloading?

PSR-4 is a PHP standard that maps namespaces to directory structures, allowing compatible classes to be loaded automatically.

Conclusion

MVC architecture and Composer are valuable concepts for professional PHP development. MVC helps separate data handling, presentation, and request coordination, while Composer makes it easier to manage external libraries and autoload classes.

By understanding both concepts, you can organize your PHP projects more effectively and prepare for working with modern frameworks such as CodeIgniter and Laravel.

Start by building a small MVC project, configure Composer autoloading, and then add a database layer and routing as your application grows.

←
Post 14 of 15
→