How Does PHP MVC Work? A Simple Explanation

MVC (Model-View-Controller): A software design pattern separating data (Model), UI (View), and logic (Controller) for scalable web apps.

Here are key steps to build a PHP MVC framework:

1. Define core files and directory structure
Set up foundational components like Controllers, Views, Models, Routing, and Database directories, Example:

- controllers/
- models/
- views/
- core/

2. Implement Routing

Routing serves as the application core, mapping URLs to controllers and actions. Typically, it parses URLs to extract controller/action names, then invokes the corresponding controller method. For example:

// routes.php
$routes = [
    '/' => 'HomeController@index',
    '/user' => 'UserController@index',
    '/user/create' => 'UserController@create',
    '/user/store' => 'UserController@store',
    '/user/edit/{id}' => 'UserController@edit',
    '/user/update/{id}' => 'UserController@update',
    '/user/delete/{id}' => 'UserController@delete',
];

3.Create Controllers

Controllers act as the application\’s logic layer, processing requests and returning responses. They receive parameters parsed by the router, then coordinate models and views to handle requests. Example:

// controllers/UserController.php
class UserController {
    public function index() {
        $users = UserModel::all();
        View::render('users/index', $users);
    }

    public function create() {
        View::render('users/create');
    }


    public function store() {
        $user = new UserModel($_POST);
        $user->save();
        redirectTo('/user');
    }

    public function edit($id) {
        $user = UserModel::getById($id);
        View::render('users/edit', $user);
    }

    public function update($id) {
        $user = UserModel::getById($id);
        $user->fill($_POST);
        $user->save();
        redirectTo('/user');

    }

    public function delete($id) {
        $user = UserModel::getById($id);
        $user->delete();
        redirectTo('/user');
    }
}

4. Implement Models

Models serve as the application\’s data layer, handling data storage and retrieval. They typically interact with databases to perform CRUD (Create, Read, Update, Delete) operations. Example:

// models/UserModel.php
class UserModel {
    public static function all() {
        $result = DB::query('SELECT * FROM users');
        return $result;
    }

    public static function getById($id) {
        $result = DB::query('SELECT * FROM users WHERE id = ?', [$id]);
        return $result[0];
    }

    public function fill($data) {
        $this->name = $data['name'];
        $this->email = $data['email'];
        $this->password = $data['password'];
    }

    public function save() {
        if ($this->id) {
            // update user
            DB::execute('UPDATE users SET name = ?, email = ?, password = ? WHERE id = ?', [
                $this->name, $this->email, $this->password, $this->id
            ]);
        } else {
            // create user
            DB::execute('INSERT INTO users (name, email, password) VALUES (?, ?, ?)', [
                $this->name, $this->email, $this->password
            ]);
        }
    }

    public function delete() {
        DB::execute('DELETE FROM users WHERE id = ?', [$this->id]);
    }

}

5. Create Views

Views constitute the presentation layer of an application, responsible for rendering user interfaces. They typically utilize template engines to generate HTML, CSS, and JavaScript outputs. Example:

<!-- views/users/index.php -->
<h1>Users List</h1>
<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Email</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($users as $user): ?>
            <tr>
                <td><?php echo $user['name']; ?></td>
                <td><?php echo $user['email']; ?></td>
                <td>
                    <a href="/user/edit/<?php echo $user['id']; ?>">Edit</a>
                    <a href="/user/delete/<?php echo $user['id']; ?>">Delete</a>
                </td>
            </tr>
        <?php endforeach; ?>
    </tbody>
</table>

6. Develop Core Components

Core features include routing, template engine, database, HTTP request and response handling. For example:

// core/Router.php
class Router {
    private static $routes = [];


    public static function addRoute($uri, $handler) {
        self::$routes[$uri] = $handler;
    }


    public static function dispatch($uri) {
        if (isset(self::$routes[$uri])) {
            $handler = self::$routes[$uri];
            list($controller, $action) = explode('@', $handler);
            $controller = 'controllers\\\\' . $controller;
            $controller = new $controller;
            $controller->$action();
        } else {
            http_response_code(404);
            echo "404 Not Found";
        }
    }
}


// core/DB.php
class DB {
    private static $conn = null;


    public static function connect() {
        if (self::$conn === null) {
            self::$conn = new PDO('mysql:host=localhost;dbname=myapp', 'root', '');
        }
    }


    public static function query($sql, $params = []) {
        self::connect();
        $stmt = self::$conn->prepare($sql);
        $stmt->execute($params);
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
        return $result;
    }


    public static function execute($sql, $params = []) {
        self::connect();
        $stmt = self::$conn->prepare($sql);
        $stmt->execute($params);
    }
}


// core/View.php
class View {
    public static function render($view, $data = []) {
        extract($data);
        include "views/$view.php";
    }
}


// core/Helpers.php
function redirectTo($uri) {
    header("Location: $uri");
}

7. Deploy the Application

Upload all files and directories to the server, then install and configure necessary software (e.g., PHP and MySQL). Set up the web server (Apache/Nginx) to use .htaccess for redirecting all requests to index.php. For example:

# .htaccess
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.php [QSA,L]

This way, when users access the application URL, the request will first reach the index.php file, then be routed to the appropriate controller and action. Finally, the controller will invoke the corresponding models and views to process the request and return the response.

The PHP MVC implementation follows a structured workflow: User requests enter through index.php, get routed to controllers, which coordinate models (data) and views (templates) to generate responses. Core components include routing, controllers, models, views, and server configuration for clean URL handling.

Add a Comment

Your email address will not be published. Required fields are marked *