ttpryg / slim-api-starter
Slim 4 API Starter with PHP 8.2 and Docker
Requires
- php: ^8.2
- firebase/php-jwt: ^7.1
- illuminate/database: ^11.0
- illuminate/events: ^11.0
- illuminate/pagination: ^11.51
- league/fractal: ^0.21.0
- monolog/monolog: ^3.10
- php-di/php-di: ^7.0
- slim/psr7: ^1.6
- slim/slim: ^4.12
- symfony/console: ^7.4
- symfony/validator: ^7.4
- ttpryg/config: dev-develop
- vlucas/phpdotenv: ^5.6
Requires (Dev)
- laravel/pint: ^1.29
- phpunit/phpunit: ^10.5
- rector/rector: ^2.6
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
A robust starter project using Slim Framework 4 with PHP 8.2, PHP-DI, Eloquent ORM, ttpryg/validation, Rector, and Docker.
Folder Structure
.
├── app/ # Main application source code
│ ├── Action/ # API Actions (ADR Pattern — invokable classes)
│ ├── Commands/ # CLI Commands (Symfony Console)
│ ├── Database/ # Migration & Seeder infrastructure
│ ├── Exception/ # Custom exception classes
│ ├── Handler/ # Custom error handler (JSON error responses)
│ ├── Middleware/ # PSR-15 Middleware (CORS, JWT, Rate Limit)
│ ├── Model/ # Eloquent Models
│ ├── Traits/ # Reusable Traits (ResponseTrait, TransformTrait)
│ └── Transformer/ # Fractal resource transformers
├── config/ # Configuration (Routes, Container, Settings, DB)
├── db/ # Database Migrations & Seeds
├── public/ # Document root (Entry point index.php)
├── storage/ # Local storage (Logs, Caches, etc.)
│ ├── logs/ # Rotating application log files
│ └── rate-limit/ # Rate limiter cache files
├── tests/ # Automated testing (PHPUnit)
├── rector.php # Rector 2 configuration
├── slim # Executable CLI tool (Symfony Console)
├── Dockerfile # PHP 8.2-FPM image configuration
├── docker-compose.yml # Orchestration App & Web Server (Nginx)
└── nginx.conf # Nginx Configuration
Key Features & Technologies
- PHP 8.2
- Slim Framework 4 & Slim PSR-7
- PHP-DI 7 (Dependency Injection)
- Eloquent ORM (Database Management)
- Illuminate Database (Database Migrations & Schema Builder)
- ttpryg/validation (Laravel-style validation & DTO validation powered by Symfony Validator)
- Symfony Console (Custom CLI Generator)
- Monolog (Rotating File-based Error Logging)
- Rector 2 (Automated Code Refactoring & Quality Checks)
- Laravel Pint (Code Styling & Formatting)
- PHPUnit (Testing)
- Docker & Nginx
- Health Check Endpoint (
GET /health) — Database ping & storage writability check
How to Run
- Clone/Download this project.
- Start the container with Docker Compose:
docker compose up -d --build
- Install dependencies using composer (inside the container):
docker exec -it slim_app composer install - Access the API at URL:
http://localhost:8080
Request Validation
This starter features Ttpryg\Validation\Validator (ttpryg/validation) built on top of Symfony Validator. It supports three flexible validation styles:
-
Array String Rules (Laravel-style string rules for convenience):
use Ttpryg\Validation\Validator; $validator = new Validator(); $validated = $validator->validate((array) $request->getParsedBody(), [ 'name' => 'required|min:3|max:255', 'email' => 'required|email', 'password' => 'required|min:8', ]);
-
Symfony Constraint Objects:
use Symfony\Component\Validator\Constraints as Assert; $validated = $validator->validate($data, [ 'email' => [new Assert\NotBlank(), new Assert\Email()], ]);
-
PHP 8 Attributes on DTOs:
use Symfony\Component\Validator\Constraints as Assert; class UserDto { public function __construct( #[Assert\NotBlank] #[Assert\Email] public string $email ) {} } $validator->validate($userDto);
-
Form Request / Validation Middleware: Dapat dibuat terpisah sebagai class yang meng-extend
App\Validation\FormRequest:use App\Validation\FormRequest; class RegisterRequest extends FormRequest { public function rules(): array { return [ 'name' => 'required|min:3', 'email' => 'required|email', ]; } }
Pasang pada route sebagai middleware:
$app->post('/users', CreateUserAction::class)->add(new RegisterRequest());
Di Action, ambil data yang sudah tervalidasi via
$request->getAttribute('validated')atau$request->getAttribute('form_request')->validated().
Application Logging & Request Tracing
This starter comes pre-configured with Monolog (RotatingFileHandler) dan RequestIdMiddleware (X-Request-Id):
- Setiap HTTP request otomatis disematkan UUID di header
X-Request-Id(atau meneruskan header dari client jika ada). - Header
X-Request-Iddisisipkan ke context logger Monolog secara otomatis untuk mempermudah audit/tracing. - Log tersimpan di:
storage/logs/app-YYYY-MM-DD.log(rotated daily, max 14 files retained). - You can inject
Psr\Log\LoggerInterfaceinto your actions to log custom messages manually:public function __construct(private \Psr\Log\LoggerInterface $logger) {} public function __invoke(...) { $this->logger->info("This is a custom log entry"); }
CLI Tool (Slim API Starter)
This project has a built-in CLI (./slim) to help accelerate the development process.
All CLI commands can be executed inside the container:
docker exec -it slim_app php slim list
Generator Commands
- Make a New Action:
Generates an Action class in PascalCase format and automatically uses
ResponseTrait.php slim make:action User/LoginAction
- Make a New Model:
Generates an Eloquent Model with the appropriate format.
php slim make:model User
- Run Migrations:
Runs all pending database migrations.
php slim migrate # or php slim migrate:run - Rollback Migrations:
Rolls back the last batch of migrations.
php slim migrate:rollback php slim migrate:rollback 3 # rollback 3 batches - Make a New Migration:
Generates a new migration class using Illuminate Schema Builder.
php slim make:migration CreateUsersTable
- Run Seeders:
Runs all database seeders.
php slim seed:run
- Create a Seeder:
Generates a new database seeder class.
php slim make:seeder UsersTableSeeder # or php slim seed:create - Make a Middleware:
Generates a PSR-15 middleware class.
php slim make:middleware Auth/CheckApiKeyMiddleware
- Make a Transformer:
Generates a Fractal resource transformer class.
php slim make:transformer UserTransformer
- Make a Job:
Generates a new queue job class for background execution.
php slim make:job SendEmailJob
- Make a Factory:
Generates an Eloquent model factory powered by FakerPHP.
php slim make:factory UserFactory
- Reset Migrations:
Rolls back all database migrations.
php slim migrate:reset
- Refresh Migrations:
Resets and re-runs all migrations (with optional
--seed).php slim migrate:refresh php slim migrate:refresh --seed
- Queue Worker Commands:
Process asynchronous background jobs:
php slim queue:work # Run queue worker php slim queue:failed # List failed jobs php slim queue:retry # Retry all failed jobs php slim queue:clear # Clear queue
Code Quality, Refactoring & Styling
This project uses Rector for automated code refactoring and Laravel Pint for PSR-12 code styling.
- Check Code Quality & Style:
docker exec -it slim_app composer fix:check - Automatically Apply Refactoring & Code Fixes:
docker exec -it slim_app composer fix
Testing
All test files are placed in the tests/ directory and tested using PHPUnit.
docker exec -it slim_app composer test
Architectural Notes
ADR Pattern (Action-Domain-Response)
This project uses the ADR pattern as an alternative to conventional MVC for API endpoints:
- Each class in
app/Actionacts independently with Single Responsibility. - Classes are implemented as invokables (using the
__invoke()magic method) so they can be routed dynamically by Slim. - Output is standardized using
ResponseTraitwhich centralizes JSON payload creation ($this->success()and$this->error()methods).
Common Container Commands
- View App Logs (Docker):
docker compose logs -f app - Enter Container Shell:
docker exec -it slim_app bash - Update Composer:
docker exec -it slim_app composer update - Refresh Autoloader:
docker exec -it slim_app composer dump-autoload