Installation
composer require codeplace-io/cloudimage-bundle
Add the bundle to config/bundles.php:
return [
// ...
Codeplace\CloudimageBundle\CloudimageBundle::class => ['all' => true],
];
Configuration Publish the default config:
php bin/console config:dump-reference Codeplace\CloudimageBundle\Configuration
Update config/packages/cloudimage.yaml with your API key and default settings:
cloudimage:
api_key: 'your-api-key-here'
default_options:
width: 800
height: 600
crop: 'fill'
First Use Case Generate a Cloudimage URL in a Twig template:
<img src="{{ path('cloudimage_url', {'url': 'https://example.com/image.jpg'}) }}" alt="Resized Image">
Or in a controller:
use Codeplace\CloudimageBundle\Service\CloudimageService;
public function showImage(CloudimageService $cloudimage)
{
$url = $cloudimage->generateUrl('https://example.com/original.jpg', [
'width' => 400,
'height' => 300,
'crop' => 'fill'
]);
return new Response("<img src='$url'>");
}
Dynamic Image Resizing Use the service in controllers to generate URLs with dynamic parameters:
$url = $cloudimage->generateUrl($productImageUrl, [
'width' => $request->get('width', 600),
'height' => $request->get('height', 400),
'format' => 'webp'
]);
Twig Integration Extend Twig with a custom filter for seamless template usage:
// src/Twig/CloudimageExtension.php
class CloudimageExtension extends \Twig\Extension\AbstractExtension
{
public function getFilters()
{
return [
new \Twig\TwigFilter('cloudimage', [$this->cloudimageService, 'generateUrl'])
];
}
}
Usage in Twig:
{{ imageUrl|cloudimage({'width': 200, 'height': 200}) }}
API Response Transformation Automatically transform image URLs in API responses using a transformer:
// src/Transformer/ImageTransformer.php
class ImageTransformer
{
public function __construct(private CloudimageService $cloudimage)
{}
public function transform($data, array $context = [])
{
if (isset($data['image_url'])) {
$data['image_url'] = $this->cloudimage->generateUrl($data['image_url'], [
'width' => 300,
'height' => 300
]);
}
return $data;
}
}
Form Field Types Create a custom form type to handle Cloudimage URLs:
// src/Form/CloudimageType.php
class CloudimageType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('originalUrl', HiddenType::class);
$builder->add('width', IntegerType::class, ['required' => false]);
$builder->add('height', IntegerType::class, ['required' => false]);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'cloudimage_service' => null,
]);
}
}
$cacheKey = 'cloudimage_url_' . md5($originalUrl . serialize($options));
$url = $cache->get($cacheKey);
if (!$url) {
$url = $cloudimage->generateUrl($originalUrl, $options);
$cache->set($cacheKey, $url, 3600); // Cache for 1 hour
}
# config/packages/dev/cloudimage.yaml
cloudimage:
api_key: '%env(CLOUDIMAGE_API_KEY_DEV)%'
API Key Exposure
%env() syntax or .env files:
cloudimage:
api_key: '%env(CLOUDIMAGE_API_KEY)%'
.env to your .gitignore and use a .env.local for local overrides.URL Encoding Issues
?, &) may break the generated Cloudimage URL.$encodedUrl = urlencode($originalUrl);
$cloudimageUrl = $cloudimage->generateUrl($encodedUrl, $options);
Default Options Override
cloudimage.yaml may conflict with explicit options passed to generateUrl().array_merge to prioritize explicit options:
$options = array_merge($this->container->getParameter('cloudimage.default_options'), $explicitOptions);
CORS Restrictions
Rate Limiting
$this->logger->debug('Generated Cloudimage URL', ['url' => $url]);
img tags for 403/404 errors (e.g., invalid API key or URL).Custom Transformers Extend the bundle to add pre/post-processing to URLs:
// src/Service/CloudimageService.php (override)
public function generateUrl($url, array $options = [])
{
$url = $this->preProcessUrl($url);
$url = parent::generateUrl($url, $options);
return $this->postProcessUrl($url);
}
Event Listeners Trigger events before/after URL generation:
// src/EventListener/CloudimageListener.php
class CloudimageListener
{
public function onCloudimageGenerate(CloudimageGenerateEvent $event)
{
$event->setOptions(array_merge($event->getOptions(), ['format' => 'webp']));
}
}
Register the listener in services.yaml:
services:
App\EventListener\CloudimageListener:
tags:
- { name: kernel.event_listener, event: cloudimage.generate, method: onCloudimageGenerate }
Dynamic Option Sources Fetch options from databases or APIs dynamically:
$options = $this->optionRepository->findByImageType($imageType);
$url = $cloudimage->generateUrl($originalUrl, $options);
Fallback Logic Handle cases where Cloudimage fails (e.g., network issues):
try {
$url = $cloudimage->generateUrl($originalUrl, $options);
} catch (\Exception $e) {
$this->logger->error('Cloudimage failed', ['error' => $e->getMessage()]);
$url = $originalUrl; // Fallback to original URL
}
How can I help you explore Laravel packages today?