Installation:
composer require daviddlv/clarifai-bundle
Ensure your composer.json has "minimum-stability": "dev" if using unreleased versions.
Enable the Bundle:
Add new ClarifaiBundle\ClarifaiBundle() to AppKernel.php (Symfony 2.x) or config/bundles.php (Symfony 3/4/5).
Configure Credentials:
Add your Clarifai API credentials to config/packages/clarifai.yaml (or config.yml in Symfony 2.x):
clarifai:
auth:
client_id: "%env(CLARIFAI_CLIENT_ID)%"
client_secret: "%env(CLARIFAI_CLIENT_SECRET)%"
Use environment variables (.env) for security.
First Use Case: Inject the Clarifai client into a service/controller and call the API:
use ClarifaiBundle\Service\ClarifaiClient;
class ImageAnalyzer
{
public function __construct(private ClarifaiClient $clarifai)
{
}
public function analyzeImage(string $imagePath): array
{
$response = $this->clarifai->getClient()->models()
->predict(ClarifaiModel::GENERAL_MODEL, $imagePath);
return $response->get('outputs')[0]['data']['concepts'];
}
}
Image Tagging/Classification:
Use the predict method with the general model or a custom model:
$concepts = $this->clarifai->predict(
ClarifaiModel::GENERAL_MODEL,
'path/to/image.jpg',
['concepts' => ['limit' => 5]] // Optional parameters
);
Custom Model Workflows:
$model = $this->clarifai->models()->create(
'my-custom-model',
ClarifaiModelType::CONCEPT,
['concept' => ['name' => 'my-concept']]
);
$results = $this->clarifai->predict($model->getId(), 'image.jpg');
Batch Processing:
Process multiple images sequentially or in parallel (using Symfony’s Messenger or Process components):
foreach ($imagePaths as $path) {
$this->clarifai->predict(ClarifaiModel::GENERAL_MODEL, $path);
}
Error Handling: Wrap API calls in try-catch blocks to handle Clarifai-specific exceptions:
try {
$response = $this->clarifai->predict(...);
} catch (ClarifaiException $e) {
// Log or retry (e.g., rate limit exceeded)
$this->logger->error('Clarifai API error: ' . $e->getMessage());
}
Integration with Forms: Use the bundle in a Symfony form to validate or auto-tag uploaded images:
$builder->add('image', FileType::class, [
'mapped' => false,
'constraints' => [
new Callback([
'callback' => [$this, 'validateImageTags'],
]),
],
]);
Caching Responses:
Cache API responses (e.g., with Symfony’s Cache component) to avoid redundant calls:
$cacheKey = md5($imagePath);
$concepts = $this->cache->get($cacheKey, function() use ($imagePath) {
return $this->clarifai->predict(ClarifaiModel::GENERAL_MODEL, $imagePath);
});
Deprecated Symfony Version: The bundle was last updated in 2016 and targets Symfony 2.x. For Symfony 3/4/5:
// src/Service/ClarifaiAdapter.php
class ClarifaiAdapter
{
public function __construct(private ClarifaiClient $legacyClient)
{
}
public function predict(string $modelId, string $imagePath): array
{
return $this->legacyClient->getClient()->models()->predict($modelId, $imagePath);
}
}
config/services.yaml:
services:
App\Service\ClarifaiAdapter:
arguments:
$legacyClient: '@clarifai.api.client'
Authentication Issues:
client_id and client_secret are correctly set in config.yml.%env(CLARIFAI_ to load from .env:
clarifai:
auth:
client_id: "%env(CLARIFAI_CLIENT_ID)%"
Rate Limiting: Clarifai enforces rate limits (e.g., 1000 requests/day for free tier). Implement exponential backoff:
use Symfony\Component\Process\Exception\ProcessFailedException;
try {
$response = $this->clarifai->predict(...);
} catch (ProcessFailedException $e) {
if (strpos($e->getMessage(), 'rate limit') !== false) {
sleep(60); // Wait 1 minute and retry
}
}
Image Format Requirements: Clarifai expects images in JPEG, PNG, or GIF format. Validate uploads:
$image = $request->file('image');
$mimeType = $image->getMimeType();
if (!in_array($mimeType, ['image/jpeg', 'image/png', 'image/gif'])) {
throw $this->createNotAcceptableException('Unsupported image format');
}
Model Management:
$this->clarifai->getClient()->models()->delete($modelId);
Environment-Specific Config:
Override the bundle’s configuration per environment (e.g., config/packages/clarifai/dev.yaml):
clarifai:
auth:
client_id: "%env(CLARIFAI_CLIENT_ID_DEV)%"
debug: true
Logging API Calls: Enable debug mode to log API requests/responses:
clarifai:
debug: true
Check logs for raw API output (useful for debugging).
Testing:
Mock the ClarifaiClient in tests using PHPUnit’s createMock:
$mockClient = $this->createMock(ClarifaiClient::class);
$mockClient->method('getClient')->willReturn($this->createMock(Clarifai\Client::class));
$this->container->set('clarifai.api.client', $mockClient);
Custom Endpoints: Extend the bundle to support Clarifai’s custom endpoints (e.g., moderation, face detection):
// src/Service/ClarifaiExtendedClient.php
class ClarifaiExtendedClient extends ClarifaiClient
{
public function detectModeration(string $imagePath): array
{
return $this->getClient()->models()
->predict(ClarifaiModel::MODERATION_MODEL, $imagePath);
}
}
Performance:
$imageStream = fopen($imagePath, 'r');
$response = $this->clarifai->predict(..., $imageStream);
fclose($imageStream);
Fallback Mechanisms: Implement a fallback to a local ML model if Clarifai fails:
try {
return $this->clarifai->predict(...);
} catch (ClarifaiException $e) {
return $this->localFallbackModel->predict($imagePath);
}
Documentation Gaps: The bundle’s README lacks examples for custom models or dataset management. Refer to:
src/Service/ClarifaiClient.php) for undocumented methods.How can I help you explore Laravel packages today?