Our client looked at the application and asked if we could automatically generate the header and footer text.
Well, of course, we can! But the question is, which service should we use, and how should we set it up? After some research, we decided to use OpenAI API, but we give ourselves the flexibility to switch to another service if needed.
In this lesson, we will implement:
- Add text generation with multiple provider support
- Add buttons to generate the text
This will be done using one of the most popular design patterns - Strategy.
Note: You can learn more about patterns in our Design Patterns in Laravel 11 course.
Creating Text Generation Service
Let's start by creating an Enum to store our supported Providers:
app/Enums/TextGenerationProviders.php
namespace App\Enums; enum TextGenerationProviders: string{ case OPENAI = 'openai'; case CLAUDE = 'claude'; // TODO case GEMINI = 'gemini'; // TODO}
This Enum will be used in a few places:
- Validate the Request to make sure the provider is supported
- Switch between providers in the Service
Next, let's create a Service to generate the text for us. We will focus on the Strategy pattern here to automatically switch between providers:
app/Services/TextGeneration/TextGenerationService.php
use App\Enums\TextGenerationProviders;use Exception; class TextGenerationService{ public function getHeader(int $userId, string $provider): string { return match ($provider) { TextGenerationProviders::OPENAI->value => (new OpenAi)->getHeader($userId), default => throw new Exception('Provider not supported'), }; } public function getFooter(int $userId, string $provider): string { return match ($provider) { TextGenerationProviders::OPENAI->value => (new OpenAi)->getFooter($userId), default => throw new Exception('Provider not supported'), }; }}
Of course, this Manager can't work without the Interface and the first implementation of the Provider:
app/Services/TextGeneration/TextGenerator.php
namespace App\Services\TextGeneration; interface TextGenerator{ public function getHeader(int $userId): string; public function getFooter(int $userId): string;}
Each of our different Generators will implement this Interface. Let's start with OpenAI:
Getting OpenAI to Work
First, we need to clarify our workflow with OpenAI. The goal here is to generate an email header and footer based on...