foundation/Claude.md
Claude 5ae612227e
Add Claude.md and Foundation skills
- Created Claude.md with comprehensive project context for AI assistant
- Added 7 skills for common development workflows:
  - docker-setup: Initialize Docker development environment
  - create-module: Scaffold new DDD modules following framework architecture
  - run-tests: Execute PHPUnit test suites with coverage
  - static-analysis: Run PHPStan and Deptrac for code quality
  - database-operations: Database import, export, and management
  - troubleshoot-docker: Diagnostic steps for Docker issues
  - debug-setup: Configure Xdebug for PHPStorm and VS Code

Each skill includes step-by-step instructions, verification steps, troubleshooting guides, and quick reference commands.
2025-11-04 21:41:27 +00:00

382 lines
11 KiB
Markdown

# Foundation Framework - Claude Context
## Project Overview
Foundation is a PHP framework built with Domain-Driven Design (DDD) principles, featuring clean architecture, modular design, and modern PHP 8+ capabilities. The framework emphasizes separation of concerns, testability, and maintainability.
## Technology Stack
- **PHP**: 8.1+
- **HTTP Framework**: Slim 4
- **Dependency Injection**: PHP-DI 7.0
- **Database**: MySQL 8.0 with PDO and Repository pattern
- **Logging**: Monolog 3.0
- **Environment Config**: phpdotenv
- **Development**: Docker + Docker Compose with Xdebug
## Architecture Principles
### Clean Architecture Layers
The framework follows strict layered architecture with clear dependency rules:
```
Domain (Pure business logic - No dependencies)
Application (Use cases - Depends on Domain only)
Infrastructure (External adapters - Depends on Application only)
```
**Layer Dependency Rules:**
- **Domain Layer**: Completely independent, no external dependencies
- **Application Layer**: Can depend on Domain and itself only
- **Infrastructure Layer**: Can depend on Application and itself only
### Module Structure
Each module follows this structure:
```
src/Modules/{ModuleName}/
├── Domain/ # Pure business logic
│ ├── {Entity}.php # Entities with identity
│ ├── {ValueObject}.php # Immutable value objects
│ └── {Repository}Interface.php # Repository contracts
├── Application/ # Use cases and orchestration
│ └── {UseCase}/
│ └── {UseCase}.php
└── Infrastructure/ # External implementations
├── Api/ # API controllers
├── Web/ # Web controllers
└── Database/ # Repository implementations
├── {Repository}.php
├── Commands/
└── Queries/
```
### Core Framework Structure
```
src/Core/
├── Application/ # Application orchestration
│ ├── Application.php # Main application class
│ ├── Kernel/HttpKernel.php # HTTP request handling
│ ├── DependencyInjection/ # DI container setup
│ ├── Bootstrapper/ # Application initialization
│ └── ServiceProvider/ # Service registration abstractions
├── ErrorHandling/ # Error handling and responses
├── Logging/ # Logging infrastructure
├── Session/ # Session management
└── Cache/ # Caching interfaces
```
## Key Concepts
### 1. Service Providers
Service Providers register services and bootstrap module-specific functionality:
- Register services in the DI container
- Bootstrap module-specific functionality
- Register HTTP routes via attribute scanning
- Auto-discovered by `ModuleLoader` from `src/Modules/*/` directories
### 2. Bootstrappers
Framework components that set up the application before handling requests:
- `ConfigInitializer` - Environment configuration
- `DatabaseInitializer` - Database connections
- `SessionInitializer` - Session management
- `ModuleLoader` - Auto-discovers and loads module service providers
### 3. Dependency Injection Container
The framework uses `InflectableContainer`, a wrapper around PHP-DI with enhanced features:
- **Container Inflection**: Automatic method invocation during object resolution
- **Smart Parameter Resolution**: Intelligent detection of class names vs static values
- **Simplified Registration**: Clean syntax for dependency declaration
**Example:**
```php
// Basic registration
$container->register(ServiceClass::class, [DependencyClass::class]);
// Interface binding
$container->bind(InterfaceClass::class, ImplementationClass::class, [Dep1::class]);
// Container inflection (automatic method calls)
$container->inflect(UnitOfWork::class)
->invokeMethod('registerPersister', [ActivityPersister::class]);
```
### 4. Attribute-Based Routing
Controllers use PHP 8+ attributes for route definitions:
- Controllers must implement `ControllerInterface`
- Routes automatically discovered during controller registration
- Available attributes: `#[Get]`, `#[Post]`, `#[Put]`, `#[Delete]`, `#[Route]`, `#[Group]`
**Example:**
```php
#[Group('/api/v1/users')]
class UserController implements ControllerInterface
{
#[Get('')]
public function index(): ResponseInterface { }
#[Get('/{id}')]
public function show(string $id): ResponseInterface { }
#[Post('', middleware: [AuthMiddleware::class])]
public function create(): ResponseInterface { }
}
```
### 5. Unit of Work Pattern
Manages database transactions and entity persistence:
- **Entity Persisters**: Handle database operations for specific entity types
- **Registration**: Via container inflection
- **Transactional**: All operations executed in single transaction
### 6. CQRS Separation
Commands (write operations) and Queries (read operations) are separated:
- Commands in `Infrastructure/Database/Commands/`
- Queries in `Infrastructure/Database/Queries/`
## Development Workflow
### Docker Environment
All development happens in Docker containers:
```bash
# Start environment
make up
# Install dependencies
make install
# Access container shell
make shell
```
**Available Services:**
- **App**: PHP 8.1 + Apache (http://localhost:8000)
- **Database**: MySQL 8.0 (port 3306)
- **phpMyAdmin**: Database management (http://localhost:8080)
### Testing
Comprehensive testing suite with PHPUnit:
```bash
make test # Run all tests
make test-unit # Unit tests only
make test-integration # Integration tests only
make test-coverage # Coverage report
```
### Code Quality
Static analysis and code quality tools:
```bash
make phpstan # PHPStan static analysis
make deptrac # Deptrac layer analysis
make static-analysis # Run both
make rector # Preview Rector changes
make rector-fix # Apply Rector changes
```
## Important Patterns
### Adding New Modules
1. Create directory: `src/Modules/{ModuleName}/`
2. Implement Domain, Application, and Infrastructure layers
3. Create `{ModuleName}ServiceProvider.php` in module root
4. ModuleLoader automatically discovers and registers it
### Creating Service Provider
```php
class MyModuleServiceProvider extends ServiceProvider
{
public function register(InflectableContainer $container): void
{
// Register services
$container->register(MyController::class, [MyService::class]);
// Bind interfaces
$container->bind(MyRepositoryInterface::class, MyRepository::class);
}
}
```
### Repository Implementation
Repositories use Commands/Queries pattern:
```php
class MyRepository implements MyRepositoryInterface
{
public function __construct(
private FetchAllQuery $fetchAll,
private SaveCommand $save,
private UnitOfWorkInterface $unitOfWork
) {}
public function save(Entity $entity): void
{
$this->unitOfWork->registerNew($entity);
$this->unitOfWork->commit();
}
}
```
## Authentication System
Two authentication modes available:
- **Session-based**: Traditional session authentication
- **JWT-based**: Token-based authentication with firebase/php-jwt
Configured via `AUTH_TYPE` environment variable.
## Internationalization
Multi-language support using Symfony Translation:
- Default locale configurable via environment
- YAML translation files
- Module-specific translations supported
## Environment Variables
Key environment variables (see `.env.example`):
```env
# Database
DB_HOST=db
DB_PORT=3306
DB_DATABASE=foundation
DB_USERNAME=foundation_user
DB_PASSWORD=foundation_password
# Authentication
AUTH_TYPE=session
JWT_SECRET=your-secret-key
JWT_ACCESS_TOKEN_TTL=900
# Locale
APP_LOCALE=en
APP_SUPPORTED_LOCALES=en,de,fr
```
## Debugging
Xdebug is configured for debugging:
- Set breakpoints in IDE
- Access application via http://localhost:8000
- Debug sessions automatically connect on port 9003
## Documentation
Complete documentation available in `./documentation/`:
- `application-core.md` - Framework architecture overview
- `application-layers.md` - Layer dependency rules
- `attribute-routing.md` - Route attribute system
- `dependency-injection.md` - DI container guide
- `docker-setup.md` - Docker environment details
- `unit-of-work.md` - Unit of Work pattern
- `authentication.md` - Authentication implementation
- `internationalization.md` - i18n setup
## Common Commands Reference
**Docker:**
```bash
make up # Start Docker environment
make down # Stop Docker environment
make shell # Access container shell
```
**Dependencies:**
```bash
make install # Install composer dependencies
make dump-autoload # Refresh autoload files
```
**Testing:**
```bash
make test # Run all tests
make test-unit # Run unit tests
make test-coverage # Generate coverage report
```
**Quality:**
```bash
make phpstan # Static analysis
make deptrac # Layer analysis
make rector # Code quality preview
```
**Database:**
```bash
# Import schema
docker compose exec -T db mysql -u foundation_user -pfoundation_password foundation < database/schema.sql
# Access MySQL CLI
docker compose exec db mysql -u foundation_user -p foundation
# Export database
docker compose exec db mysqldump -u foundation_user -pfoundation_password foundation > backup.sql
```
## Best Practices
1. **Always respect layer boundaries** - Domain must remain pure
2. **Use value objects** for primitive obsession
3. **Keep controllers thin** - Delegate to application services
4. **Use repository interfaces** in Domain layer
5. **Implement CQRS** - Separate read and write operations
6. **Write tests** - Unit tests for domain, integration for infrastructure
7. **Use attributes for routes** - Don't register routes manually
8. **Follow PSR standards** - PSR-4 autoloading, PSR-7 HTTP messages
9. **Document public APIs** - Clear docblocks for interfaces
10. **Use type hints** - Leverage PHP 8.1+ type system
## Troubleshooting
### Docker Issues
- Ensure Docker and Docker Compose are installed
- Check port conflicts (8000, 8080, 3306)
- Verify user permissions: `export USER_ID=$(id -u) && export GROUP_ID=$(id -g)`
### Database Connection Issues
- Verify database container is running: `docker compose ps`
- Check environment variables in `.env`
- Ensure database schema is imported
### Routing Issues
- Verify controller implements `ControllerInterface`
- Check route attributes syntax
- Ensure controller is registered in service provider
### Autoloading Issues
- Run `make dump-autoload` after adding new classes
- Verify PSR-4 namespace matches directory structure