JINSI YA KUTENGENEZA CONTROLLERS NA VIEWS KATIKA PHP
Controller – handles requests, logic, and interacts with models
View – handles presentation (HTML, CSS)
Goal: Keep business logic separate from presentation.
⚙️ 2. Project Folder Structure
project_root/
│
├── app/
│ ├── controllers/
│ │ └── UserController.php
│ ├── views/
│ │ └── user_view.php
│ └── models/
│ └── User.php
│
├── core/
│ └── Controller.php
├── public/
│ └── index.php
└── config/
└── config.php
🧩 3. Base Controller (core/Controller.php)
<?php
class Controller {
public function model($model){
require_once '../app/models/' . $model . '.php';
return new $model();
}
public function view($view, $data = []){
require_once '../app/views/' . $view . '.php';
}
}
model() – loads model class
view() – loads view file and passes data
🧩 4. Example Controller (app/controllers/UserController.php)
<?php
class UserController extends Controller {
public function index(){
$userModel = $this->model('User');
$users = $userModel->getAllUsers();
$this->view('user_view', ['users' => $users]);
}
public function show($id){
$userModel = $this->model('User');
$user = $userModel->getUserById($id);
$this->view('user_view', ['users' => [$user]]);
}
}
index() – shows all users
show($id) – shows single user by ID
🧩 5. Example Model (app/models/User.php)
<?php
class User {
private $pdo;
public function __construct(){
$this->pdo = new PDO("mysql:host=localhost;dbname=mvc_db;charset=utf8mb4","root","");
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public function getAllUsers(){
$stmt = $this->pdo->query("SELECT * FROM users");
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
public function getUserById($id){
$stmt = $this->pdo->prepare("SELECT * FROM users WHERE id=:id");
$stmt->execute(['id'=>$id]);
return $stmt->fetch(PDO::FETCH_ASSOC);
}
}
🧩 6. Example View (app/views/user_view.php)
<!DOCTYPE html>
<html>
<head>
<title>Users List</title>
</head>
<body>
<h2>Users</h2>
<ul>
<?php foreach($data['users'] as $user): ?>
<li><?php echo htmlspecialchars($user['username']); ?> - <?php echo htmlspecialchars($user['email']); ?></li>
<?php endforeach; ?>
</ul>
</body>
</html>
Use htmlspecialchars() to prevent XSS
$data array is passed from controller
🔑 7. Best Practices
Separate logic from presentation – controllers handle logic, views handle HTML
Sanitize output – prevent XSS attacks
Reuse views – partials or templates for headers, footers
Follow MVC structure – makes app maintainable and scalable
Pass only necessary data to views
✅ 8. Hitimisho
Controllers and views ni misingi ya MVC architecture
Separation of concerns inafanya code clean, maintainable, and scalable
Combine with models, autoloading, and routing for fully functional PHP applications
🔗 Tembelea:
👉 https://www.faulink.com/
Kwa mafunzo zaidi ya PHP, MVC structure, na best practices za controllers na views.