- Move 12 markdown files from root to docs/ subdirectories - Organize documentation by category: • docs/troubleshooting/ (1 file) - Technical troubleshooting guides • docs/deployment/ (4 files) - Deployment and security documentation • docs/guides/ (3 files) - Feature-specific guides • docs/planning/ (4 files) - Planning and improvement proposals Root directory cleanup: - Reduced from 16 to 4 markdown files in root - Only essential project files remain: • CLAUDE.md (AI instructions) • README.md (Main project readme) • CLEANUP_PLAN.md (Current cleanup plan) • SRC_STRUCTURE_IMPROVEMENTS.md (Structure improvements) This improves: ✅ Documentation discoverability ✅ Logical organization by purpose ✅ Clean root directory ✅ Better maintainability
11 KiB
CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
@docs/claude/mcp-integration.md @docs/claude/development-commands.md @docs/claude/architecture.md @docs/claude/framework-personas.md @docs/claude/scheduler-queue-pipeline.md @docs/claude/scheduler-queue-pipeline-persona.md @docs/claude/magiclinks-system.md @docs/claude/guidelines.md @docs/claude/common-workflows.md @docs/claude/error-handling.md @docs/claude/security-patterns.md @docs/claude/queue-system.md @docs/claude/event-system.md @docs/claude/async-components.md @docs/claude/console-commands.md @docs/claude/database-patterns.md @docs/claude/performance-monitoring.md @docs/claude/troubleshooting.md
MCP Server Integration 🤖
IMPORTANT: This project has a fully functional MCP (Model Context Protocol) server that provides direct access to framework internals.
Quick Access Commands:
# Start MCP server
docker exec -i php php console.php mcp:server
# Test MCP server
echo '{"jsonrpc": "2.0", "method": "initialize", "params": {}}' | docker exec -i php php console.php mcp:server
Available MCP Tools:
analyze_routes: Get all registered routes in the frameworkanalyze_container_bindings: Analyze DI container bindingsdiscover_attributes: Discover attributes by typeframework_health_check: Health check of framework componentslist_framework_modules: List all framework moduleslist_directory: List directory contents (project-scoped)read_file: Read file contents with line limitsfind_files: Find files by pattern
MCP Resources:
framework://config: Framework configuration and environment
Configuration for Claude Desktop:
{
"mcpServers": {
"custom-php-framework": {
"command": "docker",
"args": ["exec", "-i", "php", "php", "console.php", "mcp:server"],
"cwd": "/home/michael/dev/michaelschiemer"
}
}
}
Development Commands
PHP Development
composer install- Install PHP dependenciescomposer cs- Run code style checks (dry-run)composer cs-fix- Fix code style issuescomposer reload- Dump autoloader with optimization./vendor/bin/pest- Run PHP tests (using Pest testing framework)- Run phpstan always with the make command
Frontend Development
npm install- Install Node.js dependenciesnpm run dev- Start Vite development server with HTTPSnpm run build- Build production assets and copy to public/npm run preview- Preview production buildnpm run test- Run Jest testsnpm run deploy- Build and deploy assets to public/
Local Development Access
- Framework URL: https://localhost
- HTTPS Required: HTTPS is mandatory - HTTP requests will be rejected
- SSL Certificates: Automatically configured for local development
- User Agent Required: Always use a browser User-Agent header to avoid triggering firewall rules
HTTP Client Configuration
When making HTTP requests to the framework, always include a browser User-Agent:
# cURL with browser User-Agent
curl -H "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" \
https://localhost/api/endpoint
# Testing API endpoints
curl -H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36" \
-H "Content-Type: application/json" \
-d '{"key": "value"}' \
https://localhost/api/test
Docker & Environment
make up- Start all Docker containersmake down- Stop all containersmake build- Build Docker imagesmake logs- View Docker logsmake reload- Dump autoloader and restart PHP containermake console- Run console commands in Docker PHP containermake cs- Run code style checks in Dockermake cs-fix- Fix code style in Dockermake cs-fix-file FILE=path/to/file.php- Fix code style for specific filemake fix-perms- Fix file permissionsmake doctor- Check prerequisites and project health
Console Commands
php console.php- Run console applicationdocker exec php php console.php- Run console in Dockerphp console.php mcp:server- Start MCP server for AI integration
Database & Migration Commands
php console.php make:migration CreateUsersTable [Domain]- Generate new migration filephp console.php db:migrate- Apply all pending migrationsphp console.php db:rollback [steps]- Rollback migrations (default: 1 step)php console.php db:status- Show migration status across all domains
Testing
- All test files must be placed in
tests/directory - PHP test scripts (including non-Pest tests) belong in
tests/directory - Debug scripts: Place debug PHP scripts in
tests/debug/directory - Pest preferred: Always prefer Pest over PHPUnit for new tests
- No mocking: Avoid mocking - use real implementations and test data
- Directory structure: Tests should mirror source directory structure
- PHPUnit configuration in
phpunit.xml(supports both Pest and PHPUnit)
Test Directory Structure:
tests/
├── debug/ # Debug and development scripts
│ └── test-*.php # Debug scripts for testing functionality
├── Unit/ # Unit tests mirroring src/ structure
├── Feature/ # Feature/integration tests
├── tmp/ # Temporary test files (gitignored)
└── pest.php # Pest configuration
Important Test Rules:
- Temporary files: All test temporary files must be created in
tests/tmp/ortests/directory - Never create files in the project root directory during tests
- Clean up: Tests should clean up their temporary files after execution
- Isolation: Each test should use unique filenames to avoid conflicts
Architecture Overview
This is a custom PHP framework with the following key architectural patterns:
Core Components
Application Bootstrap
src/Framework/Core/Application.php- Main application class that orchestrates the request lifecyclesrc/Framework/Core/AppBootstrapper.php- Bootstraps the application and DI container- Uses event system for application lifecycle (ApplicationBooted, BeforeHandleRequest, etc.)
Dependency Injection
src/Framework/DI/Container.php- DI container interfacesrc/Framework/DI/DefaultContainer.php- Default container implementation- Supports binding, singletons, and instance registration
- Automatic dependency resolution and method invocation
HTTP & Routing
- Attribute-based routing using
#[Route]attributes src/Framework/Http/Middlewares/RoutingMiddleware.php- Core routing middleware- Middleware chain pattern for request processing
- Support for different result types (JsonResult, ViewResult, Redirect, etc.)
HttpRequest- Standard implementation of the Request interface
MCP Integration
src/Framework/Mcp/- Full MCP server implementation#[McpTool]and#[McpResource]attributes for AI integration- Automatic discovery via framework's attribute system
- Safe, project-scoped file system access for AI
Framework Principles
- No inheritance: Composition over inheritance - avoid
extendscompletely - Immutable by design: Objects should be immutable whenever possible
- Readonly everywhere: Classes and properties
readonlywhere possible - Final by default: Classes are
finalunless specifically designed for extension - Explicit dependency injection: No global state or service locators
- Modular architecture: Minimal external dependencies, clear boundaries
- Event-driven architecture: Loose coupling through domain events
- Automatic discovery: Convention over configuration with attribute scanning
[Rest of the file remains unchanged]
Exception Handling
Core Exception Handling Principles
- Detailed error context
- Centralized error logging
- Custom exception hierarchy
- Contextual error responses
- Security-focused error masking
Exception Types
FrameworkException: Base framework exceptionConfigurationException: Configuration-related errorsDatabaseException: Database connection and query errorsValidationException: Input validation failuresAuthorizationException: Access control violationsResourceNotFoundException: Missing resourcesDependencyInjectionException: DI container errorsSerializationException: Serialization/deserialization issues
Logging and Monitoring
- Automatically log all unhandled exceptions
- Include request context in error logs
- Capture stack traces for debugging
- Support for error reporting services
- Performance-aware error tracking
Error Response Handling
- Detailed errors in development
- Sanitized errors in production
- JSON and HTML error formats
- Localized error messages
- Error code mapping
Example Exception Handling
final readonly class ExceptionHandler
{
public function handle(Throwable $exception): HttpResponse
{
// Log the exception
$this->logger->error('Unhandled exception', [
'message' => $exception->getMessage(),
'type' => get_class($exception),
'trace' => $exception->getTraceAsString()
]);
// Determine appropriate response based on exception type
return match(true) {
$exception instanceof ValidationException =>
new JsonErrorResponse(
errors: $exception->getValidationErrors(),
statusCode: 422
),
$exception instanceof AuthorizationException =>
new JsonErrorResponse(
message: 'Unauthorized access',
statusCode: 403
),
$exception instanceof ResourceNotFoundException =>
new JsonErrorResponse(
message: 'Resource not found',
statusCode: 404
),
default => new JsonErrorResponse(
message: 'Internal server error',
statusCode: 500
)
};
}
}
Security Considerations
- Never expose sensitive error details in production
- Mask internal system information
- Use generic error messages for security-sensitive scenarios
- Log detailed errors server-side
- Implement rate limiting for repeated error conditions
Value Objects
CountryCode Value Object
- Represents a standardized country code (ISO 3166-1 alpha-2 and alpha-3)
- Validates and normalizes country code formats
- Ensures type safety for country code representations
## Collections and Interfaces
### PHP Collection Interfaces
- Collections implementieren IteratorAggregate + Countable
## Parameter Design
### Variadic Parameters
- Nutze variadic parameters statt arrays wo immer möglich
## Template System
- Das Templatesystem verwendet kein php sondern Html Template Komponenten und platzhalter in geschwungenen Klammern