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

Optimus Bundle Laravel Package

ckrack/optimus-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require ckrack/optimus-bundle
    

    Ensure Ckrack\OptimusBundle\CkrackOptimusBundle::class is enabled in config/bundles.php.

  2. Configuration: Generate environment variables via:

    vendor/bin/optimus spark -f env
    

    Add to .env:

    OPTIMUS_PRIME=1
    OPTIMUS_INVERSE=1
    OPTIMUS_RANDOM=0
    

    Configure config/packages/ckrack_optimus.yaml:

    ckrack_optimus:
        prime: "%env(int:OPTIMUS_PRIME)%"
        inverse: "%env(int:OPTIMUS_INVERSE)%"
        random: "%env(int:OPTIMUS_RANDOM)%"
    
  3. First Use Case: Inject the service in a controller or command:

    use Symfony\Component\DependencyInjection\ContainerInterface;
    
    public function __construct(private ContainerInterface $container) {}
    
    public function generateImage()
    {
        $optimus = $this->container->get('optimus');
        $image = $optimus->create('path/to/image.jpg')->optimize();
        return $image->save('path/to/optimized.jpg');
    }
    

Implementation Patterns

Core Workflows

  1. Image Optimization: Use the optimus service to optimize images in controllers, commands, or services:

    $optimus = $this->get('optimus');
    $optimized = $optimus->create('input.jpg')
        ->optimize()
        ->save('output.jpg');
    
  2. Dynamic Optimization: Combine with Symfony’s ParamConverter for route-based optimization:

    # config/routes.yaml
    optimize_image:
        path: /optimize/{image}
        controller: App\Controller\ImageController::optimize
        requirements:
            image: .+\.(jpg|png|gif)$
    
    // src/Controller/ImageController.php
    public function optimize(string $image, Optimus $optimus)
    {
        return $optimus->create($image)->optimize()->save("optimized_{$image}");
    }
    
  3. Batch Processing: Use Symfony’s Command component for bulk operations:

    use Symfony\Component\Console\Command\Command;
    use Symfony\Component\Console\Input\InputInterface;
    use Symfony\Component\Console\Output\OutputInterface;
    
    class OptimizeCommand extends Command
    {
        protected static $defaultName = 'app:optimize-images';
    
        public function __construct(private Optimus $optimus) {}
    
        protected function execute(InputInterface $input, OutputInterface $output): int
        {
            $images = glob('storage/images/*.jpg');
            foreach ($images as $image) {
                $this->optimus->create($image)->optimize()->save($image);
                $output->writeln("Optimized: $image");
            }
            return Command::SUCCESS;
        }
    }
    
  4. Integration with Forms: Use in form handlers to auto-optimize uploads:

    public function onKernelRequest(GetResponseEvent $event)
    {
        $request = $event->getRequest();
        if ($request->isMethod('POST') && $request->attributes->get('_route') === 'upload_image') {
            $optimus = $this->container->get('optimus');
            $file = $request->files->get('image');
            $optimized = $optimus->create($file->getPathname())->optimize();
            $optimized->moveTo($file->getClientOriginalName());
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Environment Variables:

    • Forgetting to run optimus spark -f env will leave OPTIMUS_* variables undefined.
    • Fix: Manually set defaults in config/packages/ckrack_optimus.yaml:
      ckrack_optimus:
          prime: 1
          inverse: 1
          random: 0
      
  2. ParamConverter Issues:

    • If passthrough: false, the converter will fail silently if the image isn’t found.
    • Fix: Set passthrough: true in config or handle exceptions in the controller:
      try {
          $optimized = $optimus->create($image)->optimize();
      } catch (\Exception $e) {
          $this->addFlash('error', 'Image not found or invalid.');
          return $this->redirectToRoute('home');
      }
      
  3. Service Not Found:

    • If optimus service isn’t autowired, ensure the bundle is enabled and dependencies are installed.
    • Fix: Verify composer.json includes jenssegers/optimus and ckrack/optimus-bundle.
  4. File Permissions:

    • Optimization may fail if the script lacks write permissions to the target directory.
    • Fix: Use chmod -R 775 storage/ or configure optimus to use a writable directory.

Debugging Tips

  1. Log Optimization Steps: Enable verbose logging in config/packages/ckrack_optimus.yaml:

    ckrack_optimus:
        logger: true
    

    Check logs for errors during optimization.

  2. Test Locally: Use OPTIMUS_PRIME=0 in .env to skip optimization during development:

    ckrack_optimus:
        prime: "%env(int:OPTIMUS_PRIME)%"  # Set to 0 for debugging
    
  3. Check Output Paths: Ensure save() paths are correct and directories exist:

    $optimized->save(sys_get_temp_dir() . '/optimized.jpg'); // Fallback to temp dir
    

Extension Points

  1. Custom Optimus Config: Override the optimus service in config/services.yaml:

    services:
        optimus:
            class: Jenssegers\Optimus\Optimus
            arguments:
                - { prime: 1, inverse: 1, random: 1, quality: 80 }
    
  2. Event Listeners: Trigger actions post-optimization via Symfony events:

    // src/EventListener/OptimusListener.php
    public function onKernelRequest(GetResponseEvent $event)
    {
        $request = $event->getRequest();
        if ($request->attributes->get('optimized')) {
            // Send email, log, etc.
        }
    }
    
  3. Custom ParamConverter: Extend the optimus.converter to add pre/post-processing:

    use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
    use Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\ParamConverterInterface;
    
    class CustomOptimusConverter implements ParamConverterInterface
    {
        public function supports(ParamConverter $configuration)
        {
            return $configuration->getName() === 'optimus';
        }
    
        public function apply(ParamConverter $configuration, $value)
        {
            $optimus = $this->container->get('optimus');
            return $optimus->create($value)->optimize();
        }
    }
    

    Register in services.yaml:

    services:
        app.optimus_converter:
            class: App\EventListener\CustomOptimusConverter
            tags:
                - { name: request.param_converter, converter: optimus }
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui