Building a API in PHP
Books API Structure Create folders app/ app/controllers/ app/core/ app/models/ app/models/DAOs/ app/models/DTOs/ app/models/entities/ app/utils/ config/ public/ api/composer.json Configure Composer and the PSR-4 autoload so that classes with the namespace App\ are searched inside the app/ folder. Key content: { "name": "user/api", "autoload": { "psr-4": { "App\": "app/" } } } After creating it, run this command inside the api folder: composer dump-autoload api/config/config.php Defines the base URL of the project. The router removes it from REQUEST_URI to keep only routes such as /books/get. <?php define('BASE_URL', '/proyect/api/public'); api/config/dbconf.json MySQL DB connection: { "host": "localhost", "user": "root", "password": "", "db_name": "books_db" } api/public/.htaccess Makes Apache send all routes to index.php. RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^ index.php [QSA,L] api/public/index.php This is the entry point. It loads Composer, loads the configuration and calls the router. <?php use App\Core\Router; require_once DIR . '/../vendor/autoload.php'; require_once DIR . '/../config/config.php'; (new Router())->dispatch($_SERVER['REQUEST_URI']); api/app/core/Router.php <?php namespace App\Core; class Router { protected array $routes = [ '/' => 'HomeController@index', '/books' => 'BookController@index', '/books/get' => 'BookController@getAll', '/books/getById' => 'BookController@getById', '/books/create' => 'BookController@create', '/books/update' => 'BookController@update', '/books/delete' => 'BookController@delete', ]; public function add($route, $params): void { $this->routes[$route] = $params; } public function dispatch($uri): void { $uri = parse_url(str_replace(BASE_URL, '', $uri), PHP_URL_PATH); if (!isset($this->routes[$uri])) { $this->sendNotFound(); return; } [$controller, $method] = explode('@', $this->routes[$uri]); $controller = 'App\\Controllers\\' . $controller; if (!class_exists($co