Laravel Integration Patterns

backend

Production patterns for third-party integrations, queued jobs, and reusable traits. Demonstrates API client classes, error handling with failed sync logging, and environment-aware execution.

laravel php redis
Files
app/Clients/NewsletterClient.php
1<?php
2 
3namespace App\Clients;
4 
5use App\Models\FailedIntegrationSync;
6use Illuminate\Support\Facades\Http;
7 
8class NewsletterClient
9{
10 public function __construct(
11 protected string $apiKey,
12 protected string $listId,
13 protected string $baseUrl = 'https://api.newsletter.test/v1'
14 ) {
15 }
16 
17 public function addSubscriber(
18 string $email,
19 ?string $name = null,
20 array $metadata = []
21 ): bool {
22 try {
23 $response = Http::withHeaders([
24 'Authorization' => 'Bearer ' . $this->apiKey,
25 ])
26 ->timeout(30)
27 ->post($this->baseUrl . '/lists/' . $this->listId . '/subscribers', [
28 'email' => $email,
29 'name' => $name ?? '',
30 'status' => 'subscribed',
31 'metadata' => $metadata,
32 ]);
33 
34 return $response->successful();
35 
36 } catch (\Exception $e) {
37 FailedIntegrationSync::create([
38 'provider' => 'newsletter',
39 'email' => $email,
40 'error' => $e->getMessage(),
41 'metadata' => $metadata,
42 ]);
43 
44 return false;
45 }
46 }
47 
48 public function getSubscriber(string $email): ?array
49 {
50 try {
51 $response = Http::withHeaders([
52 'Authorization' => 'Bearer ' . $this->apiKey,
53 ])
54 ->timeout(30)
55 ->get($this->baseUrl . '/lists/' . $this->listId . '/subscribers/' . md5($email));
56 
57 if ($response->successful()) {
58 return $response->json();
59 }
60 
61 return null;
62 
63 } catch (\Exception $e) {
64 return null;
65 }
66 }
67 
68 public function removeSubscriber(string $email): bool
69 {
70 try {
71 $response = Http::withHeaders([
72 'Authorization' => 'Bearer ' . $this->apiKey,
73 ])
74 ->timeout(30)
75 ->delete($this->baseUrl . '/lists/' . $this->listId . '/subscribers/' . md5($email));
76 
77 return $response->successful();
78 
79 } catch (\Exception $e) {
80 return false;
81 }
82 }
83}
Chat with me 👋🏻
William

Ask William

Available to chat