Membuat Aplikasi MVC dengan PHP #4 Controller

3 min read 8 hours ago
Published on Nov 08, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

In this tutorial, we will explore the Controller component of the MVC (Model-View-Controller) architecture using PHP. This is the fourth part of a series aimed at building a complete MVC application. Understanding the Controller's role is crucial for managing application logic, handling user input, and coordinating data flow between the Model and the View.

Step 1: Understanding the Role of the Controller

  • The Controller acts as an intermediary between the Model and the View in an MVC application.
  • It processes incoming requests, manipulates data, and returns the appropriate output to the user.
  • Familiarize yourself with the following concepts:
    • Routing: The process of directing requests to the appropriate controller actions.
    • Action Methods: Functions within the controller that respond to specific requests.

Step 2: Creating the Controller Class

  • Start by creating a new PHP file for your controller. For example, UserController.php.
  • Define the class and include necessary namespaces if applicable.
class UserController {
    public function index() {
        // Code to fetch and display user data
    }

    public function show($id) {
        // Code to display a specific user by ID
    }
}

Step 3: Implementing Routing

  • Set up routing to connect URL patterns to your controller methods.
  • Create a simple routing mechanism:
$requestUri = $_SERVER['REQUEST_URI'];

switch ($requestUri) {
    case '/users':
        $controller = new UserController();
        $controller->index();
        break;
    case '/users/show':
        $controller = new UserController();
        $controller->show($_GET['id']);
        break;
    default:
        // Handle 404 error
}

Step 4: Handling User Input

  • Use the $_GET and $_POST superglobals to retrieve user inputs.
  • Sanitize and validate inputs to prevent security vulnerabilities such as SQL injection.
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if ($id === false) {
    // Handle invalid input
}

Step 5: Connecting to the Model

  • In your controller methods, call the appropriate methods from your Model to interact with the database.
public function index() {
    $users = UserModel::getAllUsers(); // Assuming UserModel is defined elsewhere
    // Code to pass $users to the view
}

Step 6: Returning the View

  • After processing data, you need to load a view to present the output to the user.
  • Use a simple method to include the view files:
public function render($view, $data = []) {
    extract($data);
    include "views/{$view}.php";
}

Conclusion

In this tutorial, we covered the key aspects of creating a Controller in an MVC application with PHP. We discussed its role, created a basic controller class, implemented routing, handled user input, connected to the Model, and returned views.

As you continue developing your MVC application, consider exploring more advanced routing techniques and integrating additional features such as middleware for request handling. Happy coding!