TujuanMengimplementasikan arsitektur MVC pada aplikasi PHP untuk memisahkan logika bisnis (Model), tampilan (View), dan alur kontrol (Controller), sehingga aplikasi lebih terstruktur, mudah dikembangkan, dan dipelihara.
KonteksModel-View-Controller (MVC) adalah pola desain yang memisahkan aplikasi menjadi tiga komponen utama:
Hal yang DiperlukanLangkah-LangkahInisialisasi Proyek Buat struktur folder sebagai berikut:
/app
/controllers
/models
/views
/public
/config
/routes
/vendor
index.php
Konfigurasi Database (config/Database.php) Buat file konfigurasi database untuk menghubungkan aplikasi dengan database. Contoh konfigurasi:
class Database {
private $host = 'localhost';
private $db_name = 'nama_database';
private $username = 'root';
private $password = '';
public $conn;
public function getConnection() {
$this->conn = null;
try {
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $exception) {
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
Rute Aplikasi (routes/web.php) Definisikan rute yang menghubungkan URL dengan Controller:
$routes = [
'/' => 'HomeController@index',
'/user' => 'UserController@show',
];
Membuat Controller (app/controllers/HomeController.php) Controller mengelola logika dan mengarahkan data ke View:
class HomeController {
public function index() {
$data = ['title' => 'Home Page'];
require_once '../app/views/home.php';
}
}
Membuat Model (app/models/User.php) Model mengelola interaksi data dengan basis data:
class User {
private $conn;
private $table = 'users';
public function __construct($db) {
$this->conn = $db;
}
public function getUsers() {
$query = "SELECT * FROM " . $this->table;
$stmt = $this->conn->prepare($query);
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
}
Membuat View (app/views/home.php) View bertanggung jawab menampilkan data yang diberikan oleh Controller:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= $data['title']; ?></title>
</head>
<body>
<h1>Welcome to <?= $data['title']; ?></h1>
</body>
</html>
Router Utama (index.php) Router utama menangani permintaan HTTP dan menghubungkan rute dengan Controller:
require_once 'routes/web.php';
$url = $_SERVER['REQUEST_URI'];
if (array_key_exists($url, $routes)) {
$action = explode('@', $routes[$url]);
$controller = new $action[0]();
$method = $action[1];
$controller->$method();
} else {
echo "404 Not Found";
}