mivita/dev/subdomain-optimization/implementation-guide.md
2025-08-12 18:01:59 +02:00

435 lines
9.3 KiB
Markdown

# Implementation Guide - Mivita Subdomain Optimization
## Overview
This guide provides step-by-step instructions for implementing the optimized multi-domain and subdomain architecture for the Mivita application.
## Prerequisites
- Backup of current system
- Test environment available
- Access to web server configuration
- Understanding of Laravel routing and middleware
## Phase 1: Foundation Setup
### Step 1: Create New Service Classes
1. **Create DomainService**
```bash
# Copy from dev/subdomain-optimization/DomainService.php
cp dev/subdomain-optimization/DomainService.php app/Services/DomainService.php
```
2. **Create DomainContext**
```bash
# Create Domain directory and copy context
mkdir -p app/Domain
cp dev/subdomain-optimization/DomainContext.php app/Domain/DomainContext.php
```
3. **Create New Middleware**
```bash
# Copy enhanced middleware
cp dev/subdomain-optimization/DomainResolver.php app/Http/Middleware/DomainResolver.php
```
### Step 2: Register New Services
Add to `config/app.php`:
```php
'providers' => [
// ... existing providers
App\Providers\DomainServiceProvider::class,
],
```
Create `app/Providers/DomainServiceProvider.php`:
```php
<?php
namespace App\Providers;
use App\Services\DomainService;
use Illuminate\Support\ServiceProvider;
class DomainServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->singleton(DomainService::class);
}
public function boot()
{
//
}
}
```
### Step 3: Update Kernel Configuration
Add new middleware to `app/Http/Kernel.php`:
```php
protected $middleware = [
// ... existing middleware
\App\Http\Middleware\DomainResolver::class,
];
protected $middlewareGroups = [
'web' => [
// Remove old Subdomain middleware
// \App\Http\Middleware\Subdomain::class,
// ... other middleware
],
];
```
## Phase 2: Route Structure Migration
### Step 1: Create New Route Structure
```bash
# Create new directory structure
mkdir -p routes/domains/subdomains
mkdir -p routes/shared/crm
mkdir -p routes/shared/api
# Create placeholder files
touch routes/domains/main.php
touch routes/domains/shop.php
touch routes/domains/subdomains/crm.php
touch routes/domains/subdomains/portal.php
touch routes/domains/subdomains/checkout.php
touch routes/domains/subdomains/user-shops.php
touch routes/shared/legal.php
touch routes/shared/common.php
```
### Step 2: Migrate Existing Routes
1. **Legal Routes** (move to `routes/shared/legal.php`)
- Extract legal routes from all current route files
- Remove duplicates
- Standardize naming
2. **Main Domain Routes** (move to `routes/domains/main.php`)
- Extract routes from `routes/main.php`
- Clean up and organize
3. **CRM Routes** (move to `routes/domains/subdomains/crm.php`)
- Extract routes from `routes/crm.php`
- Split into sub-files for organization
4. **User Shop Routes** (move to `routes/domains/subdomains/user-shops.php`)
- Extract routes from `routes/subdomain.php`
- Remove domain-specific logic (handled by middleware)
### Step 3: Update Route Service Provider
Replace `app/Providers/RouteServiceProvider.php` with the optimized version:
```bash
cp dev/subdomain-optimization/RouteServiceProvider.php app/Providers/RouteServiceProvider.php
```
## Phase 3: Testing and Validation
### Step 1: Unit Tests
Create tests for new components:
```bash
php artisan make:test DomainServiceTest --unit
php artisan make:test DomainContextTest --unit
php artisan make:test DomainResolverTest
```
### Step 2: Feature Tests
Test each domain type:
```bash
php artisan make:test MainDomainTest
php artisan make:test CrmDomainTest
php artisan make:test UserShopDomainTest
php artisan make:test CheckoutDomainTest
php artisan make:test PortalDomainTest
```
### Step 3: Manual Testing
Test each domain type manually:
1. **Main Domain** (`mivita.care`)
- Homepage loads correctly
- Registration works
- Contact forms work
- Legal pages accessible
2. **CRM Domain** (`my.mivita.care`)
- Login system works
- User dashboard accessible
- Admin functions work
- Session management correct
3. **User Shops** (`{slug}.mivita.care`)
- Valid shops load correctly
- Invalid shops redirect properly
- Shopping cart functionality works
- Session isolation working
4. **Checkout Domain** (`checkout.mivita.care`)
- Payment processing works
- Transaction handling correct
- Security measures in place
5. **Portal Domain** (`in.mivita.care`)
- Customer login works
- Portal functionality accessible
- Data isolation correct
## Phase 4: Performance Optimization
### Step 1: Enable Caching
1. **Route Caching**
```bash
php artisan route:cache
```
2. **User Shop Caching**
- Configure Redis/Memcached
- Test cache invalidation
- Monitor cache hit rates
### Step 2: Database Optimization
1. **Add Indexes**
```sql
CREATE INDEX idx_user_shops_slug_active ON user_shops (slug, active);
CREATE INDEX idx_users_shop_active ON users (id) WHERE shop_active = 1;
```
2. **Query Optimization**
- Review N+1 queries
- Optimize user shop lookups
- Add eager loading where needed
### Step 3: Monitoring Setup
1. **Application Monitoring**
- Add performance metrics
- Monitor response times per domain
- Track error rates by domain type
2. **Cache Monitoring**
- Monitor cache hit/miss rates
- Track cache memory usage
- Set up cache warming
## Phase 5: Deployment Strategy
### Step 1: Feature Flags
Implement feature flags for gradual rollout:
```php
// In DomainResolver middleware
if (config('features.new_domain_resolver', false)) {
// Use new logic
} else {
// Fall back to old middleware
}
```
### Step 2: Blue-Green Deployment
1. **Prepare Blue Environment**
- Deploy new code to blue environment
- Test all functionality
- Verify performance metrics
2. **Switch Traffic**
- Gradually route traffic to blue
- Monitor for issues
- Ready to rollback if needed
### Step 3: Monitoring During Deployment
1. **Real-time Monitoring**
- Response times
- Error rates
- User shop accessibility
- Payment processing success
2. **Rollback Triggers**
- Error rate > 1%
- Response time > 2x baseline
- Payment failures > 0.1%
- User complaints
## Rollback Plan
### Immediate Rollback (< 5 minutes)
1. **Revert Middleware**
```php
// In Kernel.php, re-enable old middleware
\App\Http\Middleware\Subdomain::class,
```
2. **Revert Route Service Provider**
```bash
git checkout HEAD~1 app/Providers/RouteServiceProvider.php
```
3. **Clear Caches**
```bash
php artisan route:clear
php artisan config:clear
php artisan cache:clear
```
### Full Rollback (< 30 minutes)
1. **Revert All Changes**
```bash
git revert <commit-hash>
```
2. **Redeploy Previous Version**
```bash
# Deploy previous known-good version
```
3. **Verify Functionality**
- Test all domain types
- Verify user shop access
- Check payment processing
## Configuration Management
### Environment Variables
Add to `.env`:
```env
# Domain optimization feature flags
DOMAIN_RESOLVER_ENABLED=true
DOMAIN_CACHE_ENABLED=true
DOMAIN_CACHE_TTL=3600
# Monitoring
DOMAIN_MONITORING_ENABLED=true
DOMAIN_PERFORMANCE_TRACKING=true
```
### Configuration Files
Update `config/domains.php`:
```php
<?php
return [
'cache_ttl' => env('DOMAIN_CACHE_TTL', 3600),
'monitoring_enabled' => env('DOMAIN_MONITORING_ENABLED', false),
'performance_tracking' => env('DOMAIN_PERFORMANCE_TRACKING', false),
'fixed_subdomains' => ['my', 'in', 'checkout'],
'middleware_stacks' => [
'main' => ['web'],
'crm' => ['web', 'auth'],
'portal' => ['web', 'auth:customers'],
'checkout' => ['web', 'checkout'],
'user-shop' => ['web', 'subdomain'],
],
];
```
## Maintenance Procedures
### Regular Maintenance
1. **Weekly Cache Clearing**
```bash
# Clear expired user shop cache entries
php artisan domain:cache:clean
```
2. **Monthly Performance Review**
- Review response time metrics
- Check cache hit rates
- Analyze error patterns
3. **Quarterly Domain Audit**
- Review user shop validity
- Clean up inactive shops
- Update domain configurations
### Emergency Procedures
1. **User Shop Outage**
- Identify affected shops
- Clear specific cache entries
- Notify affected users
2. **Domain Resolution Issues**
- Check DNS configuration
- Verify middleware configuration
- Test domain parsing logic
3. **Performance Degradation**
- Check cache status
- Review database performance
- Scale resources if needed
## Success Metrics
### Performance Metrics
- **Response Time**: < 200ms for cached requests
- **Cache Hit Rate**: > 95% for user shop lookups
- **Error Rate**: < 0.1% across all domains
- **Uptime**: > 99.9% per domain type
### Business Metrics
- **User Shop Accessibility**: 100% for active shops
- **Payment Success Rate**: > 99.5%
- **Customer Satisfaction**: No complaints about domain issues
- **Development Velocity**: Faster feature development per domain
### Technical Metrics
- **Code Maintainability**: Reduced cyclomatic complexity
- **Test Coverage**: > 90% for domain-related code
- **Documentation**: All new components documented
- **Security**: No domain-based security vulnerabilities