Web20 University

How to use the MVC pattern in PHP Without a Framework

It’s entirely possible to implement the Model-View-Controller (MVC) pattern in PHP without using a framework. Here’s a very simplified example of how you could structure your files in an MVC pattern:

    index.php
    controller/
        controller.php
    model/
        model.php
    view/
        view.php

Model (model/model.php)

The Model represents your data structure, usually containing functions to retrieve, insert, and update information in your database.

class Model {
    public function get_data() {
        // Fetch data from the database
    }
}

## View (view/view.php) The View is responsible for rendering data onto the web page.

class View {
    public function output($data) {
        // Output data to the webpage
        echo $data;
    }
}

Controller (controller/controller.php)

The Controller handles the application logic. It interacts with the Model to retrieve data, which it then passes to the View for rendering.

class Controller {
    protected $model;
    protected $view;

    public function __construct($model, $view) {
        $this->model = $model;
        $this->view = $view;
    }

    public function load() {
        $data = $this->model->get_data();
        $this->view->output($data);
    }
}

Application Entry Point (index.php)

The index file creates instances of the Model, View, and Controller, and invokes the Controller’s load function to start the application.

include 'model/model.php';
include 'view/view.php';
include 'controller/controller.php';

$model = new Model();
$view = new View();
$controller = new Controller($model, $view);

$controller->load();

This is a very basic example and lacks many features that a full MVC framework would provide, such as routing, input validation, error handling, etc. But it should give you an idea of how you can implement the MVC pattern in PHP without a framework.

Remember that while it’s good to understand these concepts, in a production environment it’s often a better idea to use a well-established framework that has been thoroughly tested and debugged. Frameworks also provide a lot of functionality out of the box, allowing you to focus on building your application rather than reinventing the wheel.