Routing system inaruhusu:

Kupata clean URLs badala ya query strings (index.php?page=home)

Map requests kwa controllers na methods

Kurahisisha MVC architecture na scalable application

Goal: Handle requests dynamically na ku-link URL endpoints na logic.

⚙️ 2. Simple Front Controller (public/index.php)
<?php
// Start session
session_start();

// Autoload classes
spl_autoload_register(function($class){
$paths = ['../app/controllers/', '../app/models/', '../core/'];
foreach($paths as $path){
$file = $path . $class . '.php';
if(file_exists($file)){
require_once $file;
return;
}
}
});

// Parse URL
$url = isset($_GET['url']) ? explode('/', trim($_GET['url'], '/')) : [];
$controllerName = !empty($url[0]) ? ucfirst($url[0]) . 'Controller' : 'HomeController';
$method = $url[1] ?? 'index';
$params = array_slice($url, 2);

// Instantiate controller and call method
if(class_exists($controllerName)){
$controller = new $controllerName();
if(method_exists($controller, $method)){
call_user_func_array([$controller, $method], $params);
} else {
echo "❌ Method $method not found in $controllerName";
}
} else {
echo "❌ Controller $controllerName not found";
}


Example URL: http://example.com/user/view/5

Controller: UserController

Method: view

Parameter: 5

🧩 3. Example Controller (app/controllers/UserController.php)
<?php
class UserController {
public function index(){
echo "List of users";
}

public function view($id){
echo "Viewing user with ID: " . htmlspecialchars($id);
}
}


/user/index → Lists users

/user/view/5 → Shows user with ID 5

🧩 4. Example Controller (app/controllers/HomeController.php)
<?php
class HomeController {
public function index(){
echo "Welcome to the homepage!";
}
}


/ → Calls HomeController@index

🔑 5. Best Practices

Sanitize URL parameters – use htmlspecialchars() or type validation

Use controllers & methods consistently – for maintainable structure

Implement 404 handling – show custom page if controller/method not found

Support optional parameters – e.g., /post/view/5/comment/10

Combine with MVC – keep routing separate from business logic

✅ 6. Hitimisho

Routing system inafanya PHP projects kuwa scalable na clean

Allows dynamic URL mapping to controllers and methods

Can be extended with middleware, authentication checks, and role-based access

🔗 Tembelea:

👉 https://www.faulink.com/

Kwa mafunzo zaidi ya PHP, routing, na MVC architecture.