Welcome to the third lesson of our course on building an image generation service with PHP! In our previous lessons, we created the PromptManager to format user inputs into detailed prompts and the ImageManager to handle storing and processing generated images. Now, we are ready to build the core component that brings everything together: the ImageGeneratorService.
The ImageGeneratorService is the central piece of our application that will:
Connect to an external API to generate images.
Use our PromptManager to format user inputs into effective prompts.
Store generated images using our ImageManager.
Provide access to all previously generated images.
This service acts as the bridge between our application's components and the external AI service that actually creates the images. By encapsulating all the image generation logic in a dedicated service class, we maintain a clean separation of concerns in our application architecture.
In this lesson, we will implement this service step by step, from setting up the HTTP client to handling responses and errors. By the end, you will have a fully functional image generation service that you can later integrate into a PHP-based web application.
Setting Up the HTTP Client for API Access
Before we can generate images, we need to set up an HTTP client to communicate with the external API. In PHP, we can use the Guzzle library, which provides a simple interface for making HTTP requests.
First, ensure you have Guzzle installed. In a typical development environment, you would run:
Shell
composer require guzzlehttp/guzzle
Now, let's create our ImageGeneratorService class and set up the client in the constructor. We'll create a new file called ImageGeneratorService.php in the services directory:
PHP
<?phpnamespace App\Services;use GuzzleHttp\Client;use App\Models\ImageManager;use App\Models\PromptManager;class ImageGeneratorService { public $imageManager; public $client; public function __construct() { $this->imageManager = new ImageManager(); $this->client = new Client([ 'headers' => [ 'Content-Type' => 'application/json', 'x-goog-api-key' => env('GEMINI_API_KEY') ] ]); }}
This constructor performs two primary tasks:
Creating an instance of our ImageManager class to handle storing and retrieving images.
Initializing the GuzzleHTTP client with the required headers, including the API key.
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal
Implementing the Image Generation Logic
Error Handling and Service Integration
Generating images through an external API can fail for various reasons: network issues, API limits, invalid prompts, or server errors. To make our service robust, we have wrapped the API call in a try-catch block that catches any exceptions and raises a more informative RuntimeException.
This error handling is crucial for a production application, as it prevents crashes and provides meaningful error messages that help with debugging and user feedback.
Note that gemini-3.1-flash-image is specified through the configured GEMINI_BASE_URL. When the API responds successfully, the service iterates over the parts array in candidates[0]['content'] and extracts the image from the first part that contains an inlineData block. If no image part is found, the service throws an exception rather than silently returning null.
Now, let's add one more method to our service to retrieve all previously generated images:
public function getAllImages() { return $this->imageManager->getImages();}
This simple method delegates to our ImageManager's getImages() method, returning the complete list of stored images along with their associated prompts and IDs.
With these two methods, our ImageGeneratorService provides a complete interface for generating and retrieving images. The service integrates our previously built components (PromptManager and ImageManager) and connects them to the Gemini API.
ImageGeneratorService Complete Implementation
Testing the Complete Service
Summary and Practice Preview
In this lesson, we have built the ImageGeneratorService, the core component of our image generation application. This service connects our previously built components (PromptManager and ImageManager) to the Gemini API, allowing us to generate high-quality images from text prompts.
Let's review what we've learned:
We set up an HTTP client to communicate with the Gemini API using Guzzle.
We implemented the generateImage() method, which uses Guzzle to call Gemini's generateContent endpoint and extracts the image data from the returned content parts.
We added robust error handling to deal with potential API issues.
We created a method to retrieve all previously generated images.
We tested our service with a sample prompt.
The ImageGeneratorService is a crucial piece of our application architecture. It encapsulates all the logic related to image generation, providing a clean interface for other components to use. In the next lesson, we will build a controller that will use this service to handle HTTP requests in our PHP-based web application.
In the upcoming practice exercises, you will have the opportunity to work with the ImageGeneratorService, testing its functionality with different prompts and exploring how it integrates with the rest of our application. You will also experiment with error handling and see how the service behaves in various scenarios.
Remember that to use this service in a real application, you will need to:
Install the Guzzle library.
Obtain a valid API key from the Gemini API.
Store the API key securely, preferably using environment variables.
With the ImageGeneratorService in place, we are one step closer to having a complete image generation web application!
Now that our client is set up, let's implement the core method of our service: generateImage(). This method will take a user input string, format it into a detailed prompt using our PromptManager, send the request to the Gemini API, and store the resulting image using our ImageManager.
Here's the implementation:
PHP
public function generateImage(string $userInput, string $aspectRatio): string{ $prompt = PromptManager::formatPrompt($userInput, $aspectRatio); try { $apiKey = getenv("GEMINI_API_KEY"); if (!$apiKey) { throw new \RuntimeException("GEMINI_API_KEY environment variable not set."); } $endpoint = getenv("GEMINI_BASE_URL") . "?key=" . $apiKey; $response = $this->client->post($endpoint, [ 'json' => [ 'contents' => [ [ 'parts' => [ ['text' => $prompt] ] ] ], 'generationConfig' => [ 'responseModalities' => ['IMAGE', 'TEXT'] ] ] ]); $result = json_decode($response->getBody(), true); $parts = $result['candidates'][0]['content']['parts'] ?? []; $image = null; foreach ($parts as $part) { if (isset($part['inlineData'])) { $image = $part['inlineData']['data']; break; } } if ($image === null) { throw new \RuntimeException("No image data found in API response."); } return $this->imageManager->addImage($prompt, $image); } catch (\Exception $e) { throw new \RuntimeException("Error generating image: " . $e->getMessage()); }}
Let's break down what is happening in this method:
The process begins by calling PromptManager::formatPrompt() to convert the user's input into a detailed prompt using our predefined template. This ensures consistency in our image generation requests.
We build the $endpointURL using the value stored in GEMINI_BASE_URL and the API key. We then call Guzzle's post() method with the following JSON body:
contents: An array containing a single message with our prompt as a text part.
generationConfig.responseModalities: Set to ['IMAGE', 'TEXT'] to instruct the model to return image output.
From the response, we iterate over the parts array inside candidates[0]['content'], looking for a part that contains an inlineData block. The base64-encoded image data is stored in inlineData['data'].
Finally, we pass the prompt and image to our ImageManager's addImage() method, which stores it and returns the base64 string.
The method returns the base64-encoded image data, which can be used directly in web applications — for example, to display the image in an HTML<img> tag.
PHP
public function getAllImages() { return $this->imageManager->getImages();}
PHP
<?phpnamespace App\Services;use GuzzleHttp\Client;use App\Models\ImageManager;use App\Models\PromptManager;class ImageGeneratorService { public $imageManager; public $client; public function __construct() { $this->imageManager = new ImageManager(); $this->client = new Client([ 'headers' => [ 'Content-Type' => 'application/json', 'x-goog-api-key' => env('GEMINI_API_KEY') ] ]); } public function generateImage(string $userInput, string $aspectRatio): string { $prompt = PromptManager::formatPrompt($userInput, $aspectRatio); try { $apiKey = getenv("GEMINI_API_KEY"); if (!$apiKey) { throw new \RuntimeException("GEMINI_API_KEY environment variable not set."); } $endpoint = getenv("GEMINI_BASE_URL") . "?key=" . $apiKey; $response = $this->client->post($endpoint, [ 'json' => [ 'contents' => [ [ 'parts' => [ ['text' => $prompt] ] ] ], 'generationConfig' => [ 'responseModalities' => ['IMAGE', 'TEXT'] ] ] ]); $result = json_decode($response->getBody(), true); $parts = $result['candidates'][0]['content']['parts'] ?? []; $image = null; foreach ($parts as $part) { if (isset($part['inlineData'])) { $image = $part['inlineData']['data']; break; } } if ($image === null) { throw new \RuntimeException("No image data found in API response."); } return $this->imageManager->addImage($prompt, $image); } catch (\Exception $e) { throw new \RuntimeException("Error generating image: " . $e->getMessage()); } } public function getAllImages() { return $this->imageManager->getImages(); }}
Now that we have implemented our ImageGeneratorService, let's create a test script to verify that it works correctly. We will create a new file called test_service.php:
PHP
<?phprequire 'vendor/autoload.php';use App\Services\ImageGeneratorService;$userInput = "Luxury Tech Conference 2025: Innovating the Future - April 10th, New York City";$aspectRatio = "16:9";// Initialize ImageGeneratorServicetry { $imageService = new ImageGeneratorService(); $serviceResult = $imageService->generateImage($userInput, $aspectRatio); echo "Image Generated Successfully:\n"; echo $serviceResult . "\n";} catch (Exception $e) { echo "Error generating image: " . $e->getMessage() . "\n";}// Retrieve all imagesecho "\nAll Stored Images:\n";print_r($imageService->getAllImages());
In this test script, we:
Import our ImageGeneratorService class.
Define a sample user input for testing.
Create an instance of our ImageGeneratorService.
Call the generateImage() method with our sample input. The service formats the prompt internally, calls the GeminigenerateContent endpoint, and extracts the image data from the returned content parts.
Print the result (the base64-encoded image data).
Retrieve and print all stored images.
When running this script with a valid API key, you will see output similar to:
text
Image Generated Successfully:/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0a...All Stored Images:Array( [0] => Array ( [id] => 0 [prompt] => You are the lead graphic designer for 'Eventify Co.'... [image_base64] => /9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0a... ))
The base64 string would be much longer in a real application, but it has been truncated here for readability. This string represents the encoded image data extracted from the inlineData block in the Gemini response.