foundation/Claude.md
Claude 215564868f
Update Claude.md to reference skills with brief overviews
Replace detailed instructions with skill references and 2-3 sentence overviews for:
- Docker Environment → /docker-setup
- Testing → /run-tests
- Code Quality → /static-analysis
- Adding New Modules → /create-module
- Database Operations → /database-operations
- Debugging → /debug-setup
- Troubleshooting Docker → /troubleshoot-docker

This reduces duplication and keeps Claude.md concise while maintaining comprehensive guidance through skills.
2025-11-04 21:49:56 +00:00

10 KiB

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:

// 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:

#[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

See skill: /docker-setup for detailed instructions.

All development happens in Docker containers with PHP 8.1, MySQL 8.0, and phpMyAdmin. Use make up to start the environment and make install to install dependencies.

Testing

See skill: /run-tests for detailed instructions.

Comprehensive testing suite with PHPUnit supporting unit tests, integration tests, and coverage reports. Use make test to run all tests.

Code Quality

See skill: /static-analysis for detailed instructions.

Static analysis with PHPStan and Deptrac to enforce type safety and architectural boundaries. Use make static-analysis to run both tools.

Important Patterns

Adding New Modules

See skill: /create-module for detailed instructions.

Create modules following DDD principles with Domain, Application, and Infrastructure layers. The ModuleLoader automatically discovers service providers in src/Modules/*/.

Creating Service Provider

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:

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):

# 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

See skill: /debug-setup for detailed instructions.

Xdebug is pre-configured in the Docker environment for PHPStorm and VS Code. Debug sessions connect on port 9003 with automatic path mapping to /var/www/html.

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:

make up              # Start Docker environment
make down            # Stop Docker environment
make shell           # Access container shell

Dependencies:

make install         # Install composer dependencies
make dump-autoload   # Refresh autoload files

Testing:

make test            # Run all tests
make test-unit       # Run unit tests
make test-coverage   # Generate coverage report

Quality:

make phpstan         # Static analysis
make deptrac         # Layer analysis
make rector          # Code quality preview

Database:

See skill: /database-operations for detailed instructions.

# Import schema
docker compose exec -T db mysql -u foundation_user -pfoundation_password foundation < database/schema.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

See skill: /troubleshoot-docker for detailed diagnostic steps and solutions.

Common issues include port conflicts (8000, 8080, 3306), permission errors, and container startup failures. Use docker compose ps and docker compose logs to diagnose problems.

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