insideapps/application

Symfony6 structure for DDD,IA rules,best practices, user management, notifications and more...

Installs: 6

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Forks: 0

Type:project

pkg:composer/insideapps/application

1.3.6 2025-10-18 05:59 UTC

This package is auto-updated.

Last update: 2025-10-18 04:10:36 UTC


README

Symfony 6.4 PHP 8.1+ Hexagonal Architecture DDD Ready Enterprise Security

🤖 AI-Powered Development with InsideApps Guidelines

This project uses InsideApps Coding Standards specifically optimized for AI code generation. All code follows strict patterns that ensure consistency, maintainability, and quality.

📖 For AI Models (Claude, GPT, etc.):

CRITICAL: Before generating any code, read: .insideapps/insideapps_guideline.md

The guidelines provide:

  • Quick Reference - First 80 lines contain all critical rules
  • Zero Tolerance Rules - NO comments, named parameters, strict types
  • Complete Patterns - Repository, Application Service, Entity, Testing
  • Real Examples - Copy-paste ready code snippets
  • Validation Checklists - Verify compliance before delivery

🎯 Key Rules for AI:

  1. NO COMMENTS - Zero docblocks, zero inline comments
  2. Named Parameters - All method calls with 2+ params
  3. Integration Tests - Use REAL commands (NOT mocks)
  4. Final Classes - Services, repositories, controllers
  5. Repository Pattern - findById throws exception, store returns entity

📁 Project Structure:

app/
├── Course/
│   ├── Domain/          # Business logic, entities, value objects
│   ├── Application/     # Use cases, commands
│   └── Infrastructure/  # Repositories, controllers, persistence
tests/
├── Unit/                # Entity tests (mocks for commands only)
├── Application/         # Use case tests (real commands)
└── Infrastructure/      # Repository tests (real database)

🚀 Quick Start for AI Development:

1. Creating a New Entity:

# AI Prompt Example:
"Create a Course entity following InsideApps guidelines with properties: 
name, description, goal, content, hours"

# AI will generate:
- Domain/Course/Entity/Course.php
- Domain/Course/Entity/CourseId.php (extends GenericUuid)
- Domain/Course/Attributes/CourseAttributes.php
- Domain/Course/ValueObject/CourseName.php (+ all other VOs)
- Domain/Course/Event/CourseWasCreated.php
- Domain/Course/Event/CourseWasModified.php
- Domain/Course/Command/CourseCommand.php
- Domain/Course/Repository/CourseRepository.php
- Infrastructure/Storage/Doctrine/Repository/CourseDcmRepository.php
- Infrastructure/Storage/Doctrine/Type/CourseIdType.php

2. Creating Application Service:

# AI Prompt Example:
"Create CreateCourse application service following InsideApps guidelines"

# AI will generate:
- Application/Create/CreateCourse.php
- Application/Create/Command/CreateCourseCommand.php

3. Creating Integration Tests:

# AI Prompt Example:
"Create integration tests for CreateCourse following InsideApps guidelines"

# AI will generate:
- tests/Scenarios/Course/CourseScenario.php
- tests/Scenarios/Course/PersistedCourseScenario.php
- tests/Application/UseCase/CreateCourseTest.php
- tests/Infrastructure/Storage/Doctrine/Repository/CourseDcmRepositoryTest.php

✅ AI Validation Checklist:

Before accepting AI-generated code, verify:

  • [ ] No comments anywhere (docblocks, inline, multi-line)
  • [ ] All method calls with 2+ params use named parameters
  • [ ] All files start with declare(strict_types=1);
  • [ ] Entity IDs extend Shared\Domain\ValueObject\GenericUuid (NOT AbstractId)
  • [ ] Repository findById methods throw NotFoundException (NOT return null)
  • [ ] Repository store methods return entity (NOT void)
  • [ ] Integration tests use real commands (NOT mocks)
  • [ ] All classes are final (services, repositories, controllers, VOs)
  • [ ] Value Objects used instead of primitives in entities

🔗 Useful Commands:

# Validate Doctrine schema
php bin/console doctrine:schema:validate

# Run tests
php bin/phpunit

# Run specific test
php bin/phpunit tests/Application/UseCase/CreateCourseTest.php

# Check code style
vendor/bin/phpstan analyse

📋 Overview

InsideApps is a comprehensive enterprise application platform built with modern PHP 8.1+ and Symfony 6.4, following Hexagonal Architecture and Domain-Driven Design principles. The platform provides a robust foundation for business applications with advanced user management, notification systems, logging, and security features.

✨ Core Features

🔐 User Management & Authentication

  • Multi-role User System: Comprehensive role-based access control (RBAC)
  • User Registration & Profiles: Complete user lifecycle management
  • Permission Management: Granular permissions and access controls
  • Session Management: Secure session handling with timeout controls
  • Account Security: Two-factor authentication and security monitoring

🔑 Password Recovery & Security

  • Secure Password Reset: Token-based password recovery system
  • Email Verification: Account activation via secure email links
  • Password Policies: Configurable password strength requirements
  • Security Notifications: Automated alerts for security events
  • Account Lockout: Brute force protection with configurable thresholds

📧 Advanced Notification System

  • Multi-Channel Support: Email, SMS, and push notifications
  • Channel Management: Configure and manage notification channels
  • Template Engine: Rich notification templates with variables
  • Delivery Tracking: Real-time notification status monitoring
  • Batch Processing: Efficient bulk notification sending
  • Notification Dashboard: Comprehensive analytics and reporting
  • Failed Notification Handling: Automatic retry mechanisms
  • Queue Management: Asynchronous notification processing

📊 Notification Reports & Analytics

  • Real-time Dashboard: Live notification statistics and metrics
  • Delivery Reports: Detailed delivery status and analytics
  • Performance Metrics: Channel performance and success rates
  • Historical Data: Comprehensive notification history tracking
  • Export Capabilities: Data export in multiple formats
  • Custom Filters: Advanced filtering and search capabilities

🔍 Global Search System

  • Universal Search: Search across all application entities
  • Real-time Results: Instant search with live suggestions
  • Advanced Filtering: Multi-criteria search and filtering
  • Search Analytics: Track search patterns and popular queries
  • Contextual Results: Intelligent result ranking and categorization
  • Search History: User search history and saved searches

📝 Comprehensive Logging

  • Application Logs: Detailed application activity tracking
  • Security Logs: Security events and access monitoring
  • User Activity Logs: Complete user action tracking
  • System Performance Logs: Performance metrics and monitoring
  • Error Tracking: Comprehensive error logging and alerting
  • Log Analysis: Advanced log search and analysis tools
  • Log Retention: Configurable log retention policies

🏗️ Architecture & Technical Features

  • Hexagonal Architecture: Clean separation of concerns
  • Domain-Driven Design: Business-focused domain modeling
  • CQRS Pattern: Command Query Responsibility Segregation
  • Event Sourcing: Domain event tracking and replay
  • Microservice Ready: Modular architecture for scaling
  • API-First Design: RESTful APIs with comprehensive documentation

🛡️ Security Features

🔒 Enterprise Security

  • OAuth2 Integration: Secure third-party authentication
  • JWT Token Management: Stateless authentication tokens
  • CSRF Protection: Cross-site request forgery prevention
  • XSS Protection: Cross-site scripting prevention
  • SQL Injection Prevention: Parameterized queries and ORM protection
  • Rate Limiting: API and form submission rate limiting

🔐 Data Protection

  • Encryption at Rest: Sensitive data encryption
  • Secure Communication: HTTPS/TLS enforcement
  • Data Anonymization: GDPR-compliant data handling
  • Audit Trails: Complete data access and modification tracking
  • Backup Security: Encrypted backup systems

🎨 User Interface

💻 Modern Admin Interface

  • Responsive Design: Mobile-first responsive interface
  • Dark/Light Themes: Customizable UI themes
  • Dashboard Analytics: Real-time business metrics
  • Interactive Charts: Advanced data visualization
  • Bulk Operations: Efficient bulk data management
  • Export/Import: Data export and import capabilities

🎯 User Experience

  • Intuitive Navigation: Clean and logical interface design
  • Real-time Updates: Live data updates without page refresh
  • Progressive Web App: PWA capabilities for mobile experience
  • Accessibility: WCAG 2.1 AA compliance
  • Multi-language Support: Internationalization ready

🔧 Developer Features

🛠️ Development Tools

  • Code Generation: Automated entity and CRUD generation
  • Testing Framework: Comprehensive test suite with PHPUnit
  • API Documentation: Auto-generated API documentation
  • Database Migrations: Version-controlled database changes
  • Development Profiler: Symfony profiler for debugging

📦 Deployment & DevOps

  • Docker Support: Containerized deployment
  • CI/CD Pipeline: Automated testing and deployment
  • Environment Configuration: Multi-environment support
  • Performance Monitoring: Application performance tracking
  • Health Checks: System health monitoring endpoints

🚀 Performance & Scalability

Optimization

  • Database Optimization: Query optimization and indexing
  • Caching Strategy: Multi-level caching with Redis
  • Asset Optimization: Minified and compressed assets
  • CDN Integration: Content delivery network support
  • Background Jobs: Asynchronous task processing

📈 Monitoring

  • Application Metrics: Performance and usage metrics
  • Error Monitoring: Real-time error tracking and alerting
  • Uptime Monitoring: System availability tracking
  • Resource Usage: CPU, memory, and disk monitoring

🏛️ Architecture Principles

🎯 Clean Architecture

  • Domain Layer: Pure business logic and rules
  • Application Layer: Use cases and application services
  • Infrastructure Layer: External systems and frameworks
  • Dependency Inversion: Dependencies point inward to domain

🔄 Design Patterns

  • Repository Pattern: Data access abstraction
  • Factory Pattern: Object creation management
  • Observer Pattern: Event-driven architecture
  • Strategy Pattern: Pluggable algorithms and behaviors

📚 Documentation

  • API Documentation: Comprehensive REST API documentation
  • Architecture Guide: Detailed architecture documentation
  • Developer Guide: Setup and development instructions
  • User Manual: End-user documentation and tutorials
  • Deployment Guide: Production deployment instructions
  • Monolog Error Handling: Error logging and email notifications

🔧 Technology Stack

  • Backend: PHP 8.1+, Symfony 6.4
  • Database: PostgreSQL/MySQL with Doctrine ORM
  • Frontend: Bootstrap 5, JavaScript ES6+
  • Caching: Redis for session and application caching
  • Queue: Symfony Messenger for background jobs
  • Testing: PHPUnit for comprehensive test coverage
  • Security: Symfony Security component with custom extensions

🚀 Getting Started

  1. Clone the repository
  2. Install dependencies with Composer
  3. Configure environment variables
  4. Run database migrations
  5. Set up notification channels
  6. Configure user roles and permissions
  7. Start the development server

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🚨 Monolog Error 500 & Critical Email Notification System

Overview

The application is configured to handle 500 errors with dedicated logging and automatic email notifications for critical errors.

Features

1. Dedicated Error 500 Channel

All 500-level HTTP errors are logged to a dedicated error_500 channel:

  • Channel Name: error_500
  • Log File: var/log/{environment}_error_500.log
  • Rotation: 30 files maximum
  • Level: ERROR and above

2. Critical Error Email Notifications

When a CRITICAL level error occurs (HTTP 500), an email is automatically sent to administrators:

  • Subject: [CRITICAL] Application Error on {environment}
  • Format: HTML formatted email with full error details
  • Handler: Uses fingers_crossed to only send emails on critical errors
  • Additional Logging: Critical errors are also saved to var/log/{environment}_critical.log

3. Error Context Information

Each logged error includes comprehensive context:

  • Exception message and type
  • HTTP status code
  • File and line number where error occurred
  • Full stack trace
  • Request URL and HTTP method
  • Client IP address
  • User agent (for critical errors)

Quick Setup

1. Configure Email Settings

Edit config/env/.env.local (create if it doesn't exist):

# Configure your mail transport
MAILER_DSN=smtp://username:password@smtp.example.com:587

# From email for error notifications
MAILER_FROM=noreply@yourdomain.com

# Admin email to receive critical error alerts
MAILER_ADMIN_EMAIL=admin@yourdomain.com

2. Test the Configuration

# Clear cache
php bin/console cache:clear

# Test email configuration
php bin/console mailer:test admin@yourdomain.com

3. Verify Log Files

After an error occurs, check these files:

  • var/log/dev_error_500.log - All 500 errors
  • var/log/dev_critical.log - Critical errors only

Email Configuration Examples

Gmail

MAILER_DSN=smtp://username@gmail.com:app-password@smtp.gmail.com:587

SendGrid

MAILER_DSN=sendgrid://YOUR_API_KEY@default

Mailgun

MAILER_DSN=mailgun://YOUR_API_KEY:YOUR_DOMAIN@default

Amazon SES

MAILER_DSN=ses://ACCESS_KEY:SECRET_KEY@default?region=us-east-1

How It Works

Error Flow

  1. Exception Occurs: Any unhandled exception in the application
  2. ExceptionSubscriber Catches: The subscriber intercepts the exception
  3. Status Code Check: Determines if it's a 500-level error
  4. Error Logging: Logs to error_500 channel with full context
  5. Critical Check: If HTTP 500, also logs as CRITICAL
  6. Email Trigger: Critical log triggers email notification via fingers_crossed handler
  7. Email Sent: Admin receives HTML formatted error email

Example Log Entry

[2025-10-16 03:24:09] error_500.ERROR: [500] Call to undefined method {"exception":"[object] (Error(code: 0): Call to undefined method at /path/to/file.php:123)","status_code":500,"file":"/path/to/file.php","line":123,"trace":"...","url":"https://example.com/admin/dashboard","method":"GET","ip":"127.0.0.1"} []

Configuration Files

Monolog Configuration

File: config/packages/monolog.yaml

Key handlers:

  • error_500: Rotating file handler for all 500 errors
  • critical_email: Fingers crossed handler that triggers on critical errors
  • grouped_critical: Groups critical file logging and email sending
  • critical_file: Dedicated file for critical errors
  • critical_mailer: Native mailer handler for email notifications

Exception Subscriber

File: app/Shared/Infrastructure/Subscriber/ExceptionSubscriber.php

This subscriber:

  • Listens to all kernel exceptions
  • Logs all 500+ status codes to the error_500 channel
  • Logs HTTP 500 errors as CRITICAL level (triggers email)
  • Preserves existing 404 error handling

Service Configuration

File: app/Shared/Infrastructure/config/shared_services.yaml

The ExceptionSubscriber is configured to inject the error_500 logger channel.

Log Files

Development Environment

  • var/log/dev_error_500.log - All 500 errors
  • var/log/dev_critical.log - Critical errors only
  • var/log/dev.log - General application errors

Production Environment

  • var/log/prod_error_500.log - All 500 errors
  • var/log/prod_critical.log - Critical errors only
  • var/log/prod.log - General application errors

Testing

Test Error Logging

Create a test route that throws an exception:

#[Route('/test-error', name: 'test_error')]
public function testError(): Response
{
    throw new \Exception('Test error for logging');
}

Visit the route and check:

  1. var/log/dev_error_500.log - Should contain the error
  2. var/log/dev_critical.log - Should contain the critical error
  3. Email inbox - Should receive critical error email (if mailer configured)

Test Email Configuration

Run Symfony's mailer test command:

php bin/console mailer:test admin@example.com

Troubleshooting

Emails Not Sending

  1. Check MAILER_DSN: Ensure it's properly configured in .env.local
  2. Check Credentials: Verify SMTP credentials are correct
  3. Check Logs: Look for mailer errors in var/log/dev.log
  4. Test Mailer: Use php bin/console mailer:test command

Logs Not Appearing

  1. Check Permissions: Ensure var/log/ directory is writable
  2. Check Channel: Verify logger is injected correctly in ExceptionSubscriber
  3. Clear Cache: Run php bin/console cache:clear

Too Many Emails

The fingers_crossed handler ensures emails are only sent for CRITICAL level errors (HTTP 500). If you're receiving too many emails:

  1. Adjust the action_level in monolog.yaml
  2. Add excluded_http_codes to filter specific error codes
  3. Implement rate limiting using deduplication handler

Security Considerations

  1. Sensitive Data: Be careful not to log sensitive information (passwords, tokens, etc.)
  2. Email Content: Error emails may contain sensitive application details
  3. Log Rotation: Configured to keep only 30 files to manage disk space
  4. Access Control: Ensure log files are not publicly accessible

Performance

  • Minimal Overhead: Logging only occurs on errors
  • Async Email: Consider using message queue for email sending in high-traffic applications
  • Log Rotation: Automatic rotation prevents disk space issues

What Gets Logged

Each error log includes:

  • Exception message and type
  • HTTP status code
  • File and line number
  • Full stack trace
  • Request URL and method
  • Client IP address
  • User agent (for critical errors)

Production Considerations

  1. Configure Real MAILER_DSN: Replace null://null with actual mail transport
  2. Set Admin Email: Use real admin email address
  3. Monitor Log Files: Set up log monitoring/alerting
  4. Consider Rate Limiting: Add deduplication handler if needed
  5. Secure Log Access: Ensure logs are not publicly accessible

Future Enhancements

Consider implementing:

  • Integration with error tracking services (Sentry, Bugsnag, etc.)
  • Slack/Discord notifications for critical errors
  • Error rate limiting to prevent email flooding
  • Custom error pages with error tracking IDs
  • Aggregated error reports (daily/weekly summaries)

Files Modified

  1. config/packages/monolog.yaml

    • Added error_500 channel
    • Added error_500 handlers for dev and prod
    • Added critical email handler with fingers_crossed
    • Added grouped handler for critical file + email
  2. app/Shared/Infrastructure/Subscriber/ExceptionSubscriber.php

    • Added LoggerInterface dependency
    • Added 500 error detection and logging
    • Added critical error logging for HTTP 500
    • Added comprehensive error context
  3. app/Shared/Infrastructure/config/shared_services.yaml

    • Configured ExceptionSubscriber with error_500 logger
  4. config/env/.env

    • Added MAILER_FROM and MAILER_ADMIN_EMAIL variables

Support

For issues or questions about the logging configuration, refer to:

Built with ❤️ using modern PHP and Symfony