Jinsi ya Kutengeneza RESTful Routes kwa PHP (Creating RESTful Routes)
HTTP Method Action Example URL
GET Read /users
POST Create /users
PUT/PATCH Update /users/1
DELETE Delete /users/1
Goal: Design clean URLs with standard HTTP methods for CRUD operations.
⚙️ 2. Project Folder Structure
project_root/
│
├── app/
│ ├── controllers/
│ │ └── UserController.php
│ └── models/
│ └── User.php
├── core/
│ └── Router.php
├── public/
│ └── index.php
└── config/
└── config.php
🧩 3. Simple Router (core/Router.php)
<?php
class Router {
private $routes = [];
public function add($method, $uri, $callback){
$this->routes[] = ['method'=>$method, 'uri'=>$uri, 'callback'=>$callback];
}
public function dispatch($method, $uri){
foreach($this->routes as $route){
if($route['method'] === $method && preg_match("#^".$route['uri']."$#", $uri, $matches)){
array_shift($matches); // remove full match
call_user_func_array($route['callback'], $matches);
return;
}
}
header("HTTP/1.0 404 Not Found");
echo "404 Not Found";
}
}
🧩 4. Example Controller (app/controllers/UserController.php)
<?php
require_once '../app/models/User.php';
class UserController {
private $user;
public function __construct(){
$this->user = new User();
}
public function index(){
echo json_encode($this->user->getAllUsers());
}
public function show($id){
echo json_encode($this->user->getUserById($id));
}
public function store($data){
echo json_encode($this->user->createUser($data['username'], $data['email']));
}
public function update($id, $data){
echo json_encode($this->user->updateUser($id, $data['username'], $data['email']));
}
public function delete($id){
echo json_encode($this->user->deleteUser($id));
}
}
🧩 5. Front Controller (public/index.php)
<?php
require_once '../core/Router.php';
require_once '../app/controllers/UserController.php';
$router = new Router();
$userController = new UserController();
// Define routes
$router->add('GET', '/users', [$userController, 'index']);
$router->add('GET', '/users/(\d+)', [$userController, 'show']);
$router->add('POST', '/users', function(){
$data = json_decode(file_get_contents("php://input"), true);
global $userController;
$userController->store($data);
});
$router->add('PUT', '/users/(\d+)', function($id){
$data = json_decode(file_get_contents("php://input"), true);
global $userController;
$userController->update($id, $data);
});
$router->add('DELETE', '/users/(\d+)', [$userController, 'delete']);
// Dispatch request
$method = $_SERVER['REQUEST_METHOD'];
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$router->dispatch($method, $uri);
💡 Maelezo:
Uses HTTP methods to map CRUD operations
Handles JSON input/output
Clean and maintainable routing structure
🔑 6. Best Practices
Use proper HTTP methods – GET, POST, PUT/PATCH, DELETE
Return JSON responses – for API consumption
Validate input data – prevent injection and errors
Apply authentication/middleware – protect routes
Use PSR-4 autoloading – keep code organized
✅ 7. Hitimisho
RESTful routes make PHP projects scalable, maintainable, and API-ready
Clean URL design improves readability and usability
Combine with models, controllers, middleware, and JSON responses for robust web applications
🔗 Tembelea:
👉 https://www.faulink.com/
Kwa mafunzo zaidi ya PHP, RESTful API design, na best practices za modern web development.