# Backend Rules Backend development rules for PHP, databases, and APIs. ## PHP Code - Follow PSR-12 coding standard - Use strict types: `declare(strict_types=1);` - Use typed properties and return types - Maximum function length: ~40 lines - No code duplication — extract to helper functions ## API Design ### RESTful Conventions | Method | Path | Action | |--------|------|--------| | GET | /users | List users | | GET | /users/{id} | Get single user | | POST | /users | Create user | | PUT | /users/{id} | Update user | | DELETE | /users/{id} | Delete user | ### Response Format ```php // Success json_response(['data' => $user, 'status' => 200]); // Error json_response(['error' => 'Not found', 'status' => 404]); // List with pagination json_response([ 'data' => $users, 'total' => $total, 'page' => $page, 'per_page' => $perPage ]); ``` ### Status Codes - `200` OK - `201` Created - `204` No Content (successful DELETE) - `400` Bad Request - `401` Unauthorized - `403` Forbidden - `404` Not Found - `422` Unprocessable Entity (validation error) - `500` Internal Server Error ## Validation - Validate in the controller/action before business logic - Return `422` with field-specific errors on validation failure - Never trust user input — validate everything ## Database - Use PDO with parameterized queries (no string interpolation) - Use transactions for multi-step operations - Use indexes on columns used in WHERE/JOIN - Avoid N+1 queries - See `database.md` for SQLite/MariaDB/PostgreSQL portability ## Testing - Unit test business logic in isolation - Integration test API endpoints - Test happy path AND error paths - Mock database in unit tests where practical