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
PromptManagerto 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.
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:
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:
This constructor performs two primary tasks:
- Creating an instance of our
ImageManagerclass to handle storing and retrieving images. - Initializing the
GuzzleHTTPclient with the required headers, including the .
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:
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
$endpointusing the value stored in and the . We then call 's method with the following body:
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:
This simple method delegates to our 's method, returning the complete list of stored images along with their associated prompts and .
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:
In this test script, we:
- Import our
ImageGeneratorServiceclass. - Define a sample user input for testing.
- Create an instance of our
ImageGeneratorService. - Call the
generateImage()method with our sample input. The service formats thepromptinternally, calls theGeminigenerateContentendpoint, and extracts the image data from the returned contentparts. - 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:
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
HTTPclient to communicate with theGemini APIusingGuzzle. - We implemented the
generateImage()method, which usesGuzzleto callGemini'sgenerateContentendpoint and extracts the image data from the returned contentparts. - We added robust error handling to deal with potential
APIissues. - 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 requests in our -based web application.
