Lecture Notes On Class 34: PHP and MVC Pattern

Rashmi Mishra
0

 

Lecture Notes On Class 34: PHP and MVC Pattern


Objective:

  • Understand the Model-View-Controller (MVC) pattern and how it is applied in PHP.
  • Learn how to build a simple MVC application from scratch using PHP.

Outcome:

By the end of this class, students will be able to apply the MVC pattern in PHP to separate concerns and build a basic MVC application.


Introduction to MVC Pattern

The Model-View-Controller (MVC) pattern is a software architecture pattern commonly used for developing web applications. It divides an application into three interconnected components:

  • Model: Represents the data and the business logic of the application.
  • View: Handles the presentation layer; it is responsible for displaying the data to the user.
  • Controller: Acts as an intermediary between the Model and the View. It processes the user inputs and updates the Model and/or View accordingly.

Why Use MVC?

  • Separation of concerns: The MVC pattern ensures that different components of the application are managed independently, making code more maintainable and scalable.
  • Better organization: It organizes the code into three parts, making it easier for developers to work on different sections of the application simultaneously.
  • Reusable code: Logic and views are separated, so the same model can be used with multiple views.

Understanding the Components of MVC

1.   Model

o    The Model represents the data layer of the application. It contains the core logic of the application, such as fetching data from a database or processing calculations.

o    In PHP, this could be a class or a set of classes that interact with the database (using PDO or mysqli).

Example:

php

Copy code

class UserModel {

    public function getUserData($userId) {

        // Database interaction to fetch user data

        $conn = new mysqli('localhost', 'root', '', 'app_database');

        $query = "SELECT * FROM users WHERE id = $userId";

        $result = $conn->query($query);

        return $result->fetch_assoc();

    }

}

2.   View

o    The View represents the presentation layer. It is responsible for presenting data to the user. In PHP, views are typically HTML files with embedded PHP for dynamic content.

o    Views should not contain any business logic.

Example:

php

Copy code

<!-- user_profile.php -->

<h1>Welcome, <?php echo $user['name']; ?></h1>

<p>Email: <?php echo $user['email']; ?></p>

3.   Controller

o    The Controller acts as a middleman between the Model and the View. It receives input from the user, processes it (often by updating the Model), and then passes data to the View.

o    It controls the flow of the application, deciding what data to fetch from the model and which view to render.

Example:

php

Copy code

class UserController {

    public function showProfile($userId) {

        // Create an instance of the model

        $model = new UserModel();

        $user = $model->getUserData($userId);

       

        // Pass the data to the view

        include 'views/user_profile.php';

    }

}


Building a Simple MVC Application in PHP

Step 1: Set up the project structure

bash

Copy code

/mvc-example

    /controllers

        UserController.php

    /models

        UserModel.php

    /views

        user_profile.php

    /index.php

Step 2: Create the Model

In the models/UserModel.php file, create a class to fetch user data from the database.

php

Copy code

class UserModel {

    private $db;

 

    public function __construct() {

        $this->db = new mysqli('localhost', 'root', '', 'mvc_example');

    }

 

    public function getUserData($userId) {

        $query = "SELECT * FROM users WHERE id = $userId";

        $result = $this->db->query($query);

        return $result->fetch_assoc();

    }

}

Step 3: Create the Controller

In the controllers/UserController.php file, create a class that will handle requests, interact with the model, and pass data to the view.

php

Copy code

class UserController {

    public function showProfile($userId) {

        // Instantiate the model

        $userModel = new UserModel();

        $user = $userModel->getUserData($userId);

 

        // Pass the data to the view

        include 'views/user_profile.php';

    }

}

Step 4: Create the View

In the views/user_profile.php file, create the HTML structure that will display the user data.

php

Copy code

<h1>User Profile</h1>

<p>Name: <?php echo $user['name']; ?></p>

<p>Email: <?php echo $user['email']; ?></p>

Step 5: Set up the Entry Point (index.php)

The index.php file will be the entry point for the application. It will handle the routing, instantiate the appropriate controller, and call the correct method.

php

Copy code

require_once 'models/UserModel.php';

require_once 'controllers/UserController.php';

 

if (isset($_GET['user_id'])) {

    $userId = $_GET['user_id'];

    $controller = new UserController();

    $controller->showProfile($userId);

} else {

    echo 'User ID not provided';

}


Conclusion

In this class, we covered the basic structure and components of the MVC design pattern:

  • Model: Deals with data and business logic.
  • View: Displays the user interface.
  • Controller: Handles user input and controls the flow of the application.

We also built a simple MVC application that interacts with a database to fetch and display user data. This approach can be scaled to more complex applications by adding more models, views, and controllers.


Assignments:

1.   Extend the application to include a feature where users can update their profile.

2.   Implement a simple routing system to handle multiple pages (e.g., user profile, homepage, etc.).


By understanding and applying the MVC pattern in PHP, you will be able to develop better-organized, maintainable, and scalable web applications.


Post a Comment

0Comments

Post a Comment (0)