Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Cloudimage Bundle Laravel Package

codeplace-io/cloudimage-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require codeplace-io/cloudimage-bundle
    

    Add the bundle to config/bundles.php:

    return [
        // ...
        Codeplace\CloudimageBundle\CloudimageBundle::class => ['all' => true],
    ];
    
  2. 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'
    
  3. 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'>");
    }
    

Implementation Patterns

Common Workflows

  1. 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'
    ]);
    
  2. 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}) }}
    
  3. 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;
        }
    }
    
  4. 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,
            ]);
        }
    }
    

Integration Tips

  • Cache Generated URLs: Store generated Cloudimage URLs in cache to avoid redundant API calls.
    $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
    }
    
  • Environment-Specific Config: Use Symfony’s parameter bag to switch between dev/prod Cloudimage settings.
    # config/packages/dev/cloudimage.yaml
    cloudimage:
        api_key: '%env(CLOUDIMAGE_API_KEY_DEV)%'
    
  • Validation: Validate Cloudimage URLs in forms or DTOs to ensure they’re properly formatted before processing.

Gotchas and Tips

Pitfalls

  1. API Key Exposure

    • Risk: Hardcoding API keys in config files can expose them in version control.
    • Fix: Use Symfony’s %env() syntax or .env files:
      cloudimage:
          api_key: '%env(CLOUDIMAGE_API_KEY)%'
      
    • Tip: Restrict .env to your .gitignore and use a .env.local for local overrides.
  2. URL Encoding Issues

    • Risk: Special characters in image URLs (e.g., ?, &) may break the generated Cloudimage URL.
    • Fix: URL-encode the original URL before passing it to the service:
      $encodedUrl = urlencode($originalUrl);
      $cloudimageUrl = $cloudimage->generateUrl($encodedUrl, $options);
      
  3. Default Options Override

    • Risk: Default options in cloudimage.yaml may conflict with explicit options passed to generateUrl().
    • Fix: Use array_merge to prioritize explicit options:
      $options = array_merge($this->container->getParameter('cloudimage.default_options'), $explicitOptions);
      
  4. CORS Restrictions

    • Risk: If Cloudimage’s CORS policy blocks your domain, generated URLs won’t load in the browser.
    • Fix: Ensure your domain is whitelisted in Cloudimage’s dashboard or use a proxy.
  5. Rate Limiting

    • Risk: Excessive API calls may hit Cloudimage’s rate limits.
    • Fix: Implement caching for generated URLs (as shown above) and monitor usage.

Debugging

  • Log Generated URLs: Add debug logs to verify URLs before rendering:
    $this->logger->debug('Generated Cloudimage URL', ['url' => $url]);
    
  • Validate API Key: Test the API key manually via Cloudimage’s API tester to ensure it’s active.
  • Check Response Headers: Use browser dev tools to inspect img tags for 403/404 errors (e.g., invalid API key or URL).

Extension Points

  1. 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);
    }
    
  2. 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 }
    
  3. Dynamic Option Sources Fetch options from databases or APIs dynamically:

    $options = $this->optionRepository->findByImageType($imageType);
    $url = $cloudimage->generateUrl($originalUrl, $options);
    
  4. 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
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor