PHP code example of litepie / notifications

1. Go to this page and download the library: Download litepie/notifications library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

litepie / notifications example snippets


use Litepie\Notifications\Facades\NotificationManager;

// Send a simple notification
NotificationManager::send($user, 'welcome', [
    'name' => $user->name,
    'email' => $user->email
]);

// Send via specific channels
NotificationManager::via(['mail', 'database'])
    ->send($user, 'order_confirmed', $orderData);

// Send to multiple users
NotificationManager::sendBulk($users, 'newsletter', $content);

// Database notifications with custom data
NotificationManager::via(['database'])->send($user, 'custom', [
    'title' => 'New Message',
    'message' => 'You have a new message from support',
    'action_url' => '/messages/123',
    'icon' => 'mail'
]);

// Email with custom template
NotificationManager::via(['mail'])->send($user, 'invoice', [
    'invoice_number' => 'INV-001',
    'amount' => '$99.99',
    'due_date' => '2025-09-01'
]);

// SMS notifications
NotificationManager::via(['sms'])->send($user, 'verification', [
    'code' => '123456',
    'expires_in' => '10 minutes'
]);

// Slack notifications
NotificationManager::via(['slack'])->send($channel, 'deployment', [
    'environment' => 'production',
    'version' => 'v2.1.0',
    'status' => 'success'
]);

// Push notifications
NotificationManager::via(['push'])->send($user, 'breaking_news', [
    'title' => 'Breaking News',
    'body' => 'Important update available',
    'data' => ['article_id' => 123]
]);

use Litepie\Notifications\Facades\TemplateManager;

// Create a new template
TemplateManager::create('welcome_email', [
    'subject' => 'Welcome to {{app_name}}!',
    'content' => 'Hello {{name}}, welcome to our platform!',
    'channel' => 'mail',
    'language' => 'en'
]);

// Use template with variables
NotificationManager::send($user, 'welcome_email', [
    'name' => $user->name,
    'app_name' => config('app.name')
]);

// Multi-language templates
TemplateManager::create('welcome_email', [
    'subject' => 'Bienvenue sur {{app_name}}!',
    'content' => 'Bonjour {{name}}, bienvenue sur notre plateforme!',
    'channel' => 'mail',
    'language' => 'fr'
]);

// Queue notifications for better performance
NotificationManager::queue($users, 'bulk_update', $data);

// Schedule notifications
NotificationManager::schedule($user, 'reminder', $data, now()->addHours(24));

// Bulk queue with custom queue
NotificationManager::onQueue('high-priority')
    ->sendBulk($urgentUsers, 'security_alert', $alertData);

use Litepie\Notifications\Facades\AiOptimizer;

// Get optimal delivery time for user
$optimalTime = AiOptimizer::optimizeDeliveryTime($user->id, 'email');
// Returns: ['optimal_hours' => [9, 14, 18], 'confidence' => 0.85]

// Schedule notification for optimal time
$nextOptimalTime = collect($optimalTime['optimal_hours'])
    ->map(fn($hour) => today()->setHour($hour))
    ->first(fn($time) => $time->isFuture());

NotificationManager::schedule($user, 'newsletter', $data, $nextOptimalTime);

// Personalize notification content using AI
$notification = [
    'subject' => 'Check out our new features!',
    'content' => 'We have some exciting updates for you.',
    'cta' => 'Learn More'
];

$personalizedNotification = AiOptimizer::personalizeContent($notification, $user->id);
// AI adapts content based on user behavior and preferences

NotificationManager::send($user, $personalizedNotification);

// Check if content might be flagged as spam
$spamResult = AiOptimizer::detectSpam([
    'subject' => 'FREE MONEY! URGENT! CLICK NOW!',
    'content' => 'You won $1,000,000! Click here immediately!'
]);

if ($spamResult['is_spam']) {
    // Revise content or skip sending
    Log::warning('Spam detected', $spamResult['reasons']);
} else {
    NotificationManager::send($user, 'promotion', $data);
}

// Predict engagement likelihood before sending
$engagementScore = AiOptimizer::predictEngagement($notification, $user->id);

if ($engagementScore > 0.7) {
    // High likelihood of engagement - send immediately
    NotificationManager::send($user, 'promotion', $data);
} else {
    // Low engagement - try different time or content
    $betterTime = AiOptimizer::optimizeDeliveryTime($user->id, 'email');
    NotificationManager::schedule($user, 'promotion', $data, $betterTime);
}

use Litepie\Notifications\Facades\AnalyticsManager;

// Get real-time dashboard data
$metrics = AnalyticsManager::getRealTimeMetrics();
/*
Returns:
[
    'notifications_last_hour' => 1250,
    'success_rate_last_hour' => 98.5,
    'avg_delivery_time' => 2.3, // seconds
    'active_channels' => ['mail', 'sms', 'push'],
    'queue_size' => 45,
    'failed_jobs_count' => 2
]
*/

// Get comprehensive delivery stats
$stats = AnalyticsManager::getDeliveryStats([
    'date_from' => '2025-08-01',
    'date_to' => '2025-08-22',
    'channel' => 'email'
]);

/*
Returns:
[
    'total_sent' => 10000,
    'successful' => 9850,
    'failed' => 150,
    'success_rate' => 98.5,
    'channels' => ['mail' => 7000, 'sms' => 2000, 'push' => 1000],
    'hourly_breakdown' => [9 => 500, 14 => 800, 18 => 600],
    'top_templates' => ['welcome' => 3000, 'newsletter' => 2500]
]
*/

// Track user engagement
$engagement = AnalyticsManager::getEngagementMetrics([
    'date_from' => '2025-08-01',
    'channel' => 'email'
]);

/*
Returns:
[
    'open_rate' => 25.5,
    'click_rate' => 8.2,
    'conversion_rate' => 3.1,
    'unsubscribe_rate' => 0.5,
    'engagement_by_channel' => [...],
    'optimal_send_times' => [9, 14, 18]
]
*/

// Generate custom analytics report
$report = AnalyticsManager::generateCustomReport([
    'total_sent',
    'success_rate',
    'engagement_rate'
], [
    'date_from' => '2025-08-01',
    'channel' => 'email'
], 'csv');

// Export to CSV for further analysis
file_put_contents('notification_report.csv', $report['data']);

use Litepie\Notifications\Facades\WebhookManager;

// Register webhook for all events
$endpoint = WebhookManager::registerEndpoint('https://your-app.com/webhooks');

// Register webhook for specific events
$endpoint = WebhookManager::registerEndpoint(
    'https://your-app.com/webhooks/notifications',
    ['notification.sent', 'notification.failed', 'notification.opened'],
    ['Authorization' => 'Bearer your-token']
);

// In your webhook controller
public function handleNotificationWebhook(Request $request)
{
    // Verify webhook signature
    $signature = $request->header('X-Webhook-Signature');
    $timestamp = $request->header('X-Webhook-Timestamp');
    
    // Process webhook data
    $event = $request->input('event');
    $data = $request->input('data');
    
    switch ($event) {
        case 'notification.sent':
            // Handle successful delivery
            $this->handleDeliverySuccess($data);
            break;
            
        case 'notification.failed':
            // Handle delivery failure
            $this->handleDeliveryFailure($data);
            break;
            
        case 'notification.opened':
            // Track engagement
            $this->trackEngagement($data);
            break;
    }
    
    return response()->json(['status' => 'received']);
}

use Litepie\Notifications\Facades\TenantManager;

// Set current tenant (auto-resolves from subdomain, headers, or user)
TenantManager::setTenant('tenant-123');

// All notifications are now scoped to this tenant
NotificationManager::send($user, 'welcome', $data);

// Create new tenant
$tenant = TenantManager::createTenant([
    'name' => 'Acme Corp',
    'slug' => 'acme',
    'configuration' => [
        'mail_from' => '[email protected]',
        'brand_color' => '#007bff'
    ],
    'limits' => [
        'notifications_per_hour' => 5000,
        'notifications_per_day' => 50000
    ]
]);

// Check tenant limits before sending
if (TenantManager::checkTenantLimits('tenant-123', 'notifications_per_hour')) {
    NotificationManager::send($user, 'promotion', $data);
} else {
    Log::warning('Tenant rate limit exceeded', ['tenant' => 'tenant-123']);
}

// Get tenant usage statistics
$usage = TenantManager::getTenantUsage('tenant-123');
/*
Returns:
[
    'hourly_notifications' => 1250,
    'daily_notifications' => 15000,
    'storage_mb' => 45.2,
    'active_channels' => ['mail', 'sms']
]
*/

// Configure rate limits per user/tenant
NotificationManager::rateLimit('user:' . $user->id, 10, 60) // 10 per minute
    ->send($user, 'verification', $data);

// Global rate limiting
NotificationManager::rateLimit('global', 1000, 3600) // 1000 per hour
    ->sendBulk($users, 'newsletter', $data);

// Automatic content validation and sanitization
$cleanData = NotificationManager::validateAndClean([
    'title' => $request->input('title'),
    'message' => $request->input('message'),
    'url' => $request->input('url')
]);

NotificationManager::send($user, 'custom', $cleanData);

use Litepie\Notifications\Contracts\ChannelContract;
use Litepie\Notifications\Data\NotificationData;

class DiscordChannel implements ChannelContract
{
    public function send($notifiable, NotificationData $notification): array
    {
        // Implement Discord webhook sending
        $response = Http::post('https://discord.com/api/webhooks/...', [
            'content' => $notification->content,
            'username' => config('app.name')
        ]);
        
        return [
            'status' => $response->successful() ? 'sent' : 'failed',
            'id' => $response->json('id'),
            'timestamp' => now()
        ];
    }
    
    public function supports(string $type): bool
    {
        return $type === 'discord';
    }
    
    public function validate(array $config): bool
    {
        return isset($config['webhook_url']);
    }
}

// In your service provider
use Litepie\Notifications\Facades\ChannelManager;

public function boot()
{
    ChannelManager::extend('discord', function ($config) {
        return new DiscordChannel($config);
    });
}

// Send via custom channel
NotificationManager::via(['discord'])->send($user, 'server_alert', [
    'message' => 'Server deployment completed successfully!',
    'environment' => 'production'
]);

use Tests\TestCase;
use Litepie\Notifications\Facades\NotificationManager;

class NotificationTest extends TestCase
{
    public function test_can_send_email_notification()
    {
        $user = User::factory()->create();
        
        $result = NotificationManager::via(['mail'])
            ->send($user, 'welcome', ['name' => $user->name]);
            
        $this->assertEquals('sent', $result['status']);
        $this->assertDatabaseHas('notification_logs', [
            'notifiable_id' => $user->id,
            'template' => 'welcome',
            'channel' => 'mail',
            'status' => 'sent'
        ]);
    }
}

// config/notifications.php
return [
    'channels' => [
        'mail' => [
            'driver' => 'smtp',
            'retry_attempts' => 3,
            'retry_delay' => 60, // seconds
            'templates_path' => resource_path('views/notifications/mail'),
        ],
        'sms' => [
            'provider' => 'twilio', // or 'nexmo'
            'retry_attempts' => 2,
            'rate_limit' => 100, // per minute
        ],
        'slack' => [
            'retry_attempts' => 3,
            'timeout' => 30, // seconds
        ],
    ],
    
    'ai' => [
        'enabled' => env('NOTIFICATION_AI_ENABLED', false),
        'provider' => 'openai', // or 'custom'
        'cache_predictions' => true,
        'cache_ttl' => 3600,
    ],
    
    'analytics' => [
        'enabled' => true,
        'retention_days' => 90,
        'real_time_updates' => true,
    ],
    
    'webhooks' => [
        'enabled' => true,
        'timeout' => 30,
        'max_failures' => 5,
        'retry_delay' => [60, 300, 900], // seconds
    ]
];

// Add to your health check endpoint
use Litepie\Notifications\Facades\AnalyticsManager;

public function healthCheck()
{
    $metrics = AnalyticsManager::getRealTimeMetrics();
    
    return [
        'notification_system' => [
            'status' => $metrics['success_rate_last_hour'] > 95 ? 'healthy' : 'degraded',
            'queue_size' => $metrics['queue_size'],
            'failed_jobs' => $metrics['failed_jobs_count'],
            'last_hour_sent' => $metrics['notifications_last_hour']
        ]
    ];
}

// Set up alerts for system issues
if ($metrics['success_rate_last_hour'] < 90) {
    NotificationManager::via(['slack'])
        ->send('#alerts', 'system_alert', [
            'message' => 'Notification success rate below 90%',
            'success_rate' => $metrics['success_rate_last_hour'],
            'failed_jobs' => $metrics['failed_jobs_count']
        ]);
}
bash
php artisan vendor:publish --provider="Litepie\Notifications\NotificationServiceProvider" --tag="config"
bash
php artisan vendor:publish --provider="Litepie\Notifications\NotificationServiceProvider" --tag="migrations"
php artisan migrate
bash
# Set up queue workers
php artisan queue:work --queue=notifications,high-priority,default

# Set up scheduler for cleanup
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1

# Set up monitoring
php artisan notifications:monitor --alerts=slack