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

Avatarize Bundle Laravel Package

birkof/avatarize-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require birkof/avatarize
    

    Ensure your composer.json includes "birkof/avatarize": "^0.2" (or latest stable).

  2. Enable the Bundle (Symfony 4+): Add to config/bundles.php:

    return [
        // ...
        Birkof\AvatarizeBundle\AvatarizeBundle::class => ['all' => true],
    ];
    
  3. First Use Case: Generate an avatar URL for a user named "John Doe":

    use Birkof\AvatarizeBundle\Avatarize;
    
    $avatarize = new Avatarize();
    $url = $avatarize->getAvatarUrl('John Doe');
    // Outputs: e.g., "https://api.adorable.io/avatars/285/jd.png"
    

Key Configuration

Check config/packages/avatarize.yaml (auto-generated) for default settings like:

  • Base URL (e.g., https://api.adorable.io/avatars/)
  • Size (default: 285)
  • Fallback behavior (e.g., emoji support).

Implementation Patterns

Core Workflows

  1. Generating Avatars:

    • Basic Usage:
      $avatarize->getAvatarUrl('Elon Musk'); // "https://api.adorable.io/avatars/285/em.png"
      
    • Custom Size:
      $avatarize->setSize(150)->getAvatarUrl('Jane Smith'); // "https://api.adorable.io/avatars/150/js.png"
      
    • UTF-8/Emoji Support:
      $avatarize->getAvatarUrl('🚀 Rocket'); // Handles non-ASCII characters
      
  2. Integration with Twig: Add to services.yaml:

    services:
        avatarize.twig:
            class: Birkof\AvatarizeBundle\Twig\AvatarizeExtension
            tags: ['twig.extension']
    

    Use in templates:

    <img src="{{ avatarize('Taylor Swift', 100) }}" alt="Avatar">
    
  3. Dynamic Fallbacks: Override default behavior (e.g., for empty names):

    $avatarize->setFallback('?default=1'); // Appends to URL
    

Advanced Patterns

  • Caching: Cache generated URLs (e.g., with Symfony Cache component) to avoid redundant API calls.

    $cache = $cachePool->getItem('avatar_john_doe');
    if (!$cache->isHit()) {
        $url = $avatarize->getAvatarUrl('John Doe');
        $cache->set($url);
        $cachePool->save($cache);
    }
    
  • Custom Services: Extend the Avatarize class for project-specific logic:

    class CustomAvatarize extends Avatarize {
        public function getTeamAvatarUrl(string $name, string $teamColor) {
            return $this->getAvatarUrl($name) . '&bg=' . $teamColor;
        }
    }
    
  • API Wrapper: Use the underlying LasseRafn/php-initials library directly for non-URL generation:

    use LasseRafn\Initials\Initials;
    
    $initials = new Initials();
    $initials->get('Marie Curie'); // "MC"
    

Gotchas and Tips

Pitfalls

  1. Deprecated Base URL: The bundle defaults to adorable.io, which may change or deprecate. Monitor their status and override the base URL in config:

    # config/packages/avatarize.yaml
    avatarize:
        base_url: 'https://new-api.example.com/avatars/'
    
  2. UTF-8 Edge Cases: While UTF-8 is supported, emojis may not render correctly in all avatar services. Test with your target API (e.g., api.adorable.io vs. api.dicebear.com).

  3. Symfony 5+ Compatibility: The bundle lacks explicit Symfony 5+ support. Verify compatibility by checking:

    • composer.json for PHP 7.4+ constraints.
    • AvatarizeBundle::class registration in bundles.php.
  4. CORS Issues: If using a CDN, ensure the avatar service’s CORS policy allows your domain. Fallback to a local service (e.g., dicebear.com) if needed.

Debugging

  • Invalid URLs: Log the raw URL before generation to debug:

    $url = $avatarize->getAvatarUrl('Test User');
    \Log::debug('Generated URL:', ['url' => $url]);
    

    Common issues:

    • Missing size parameter (e.g., 285).
    • Invalid characters in names (e.g., unencoded & or spaces).
  • Fallback Behavior: If avatars fail to render, check the fallback config or implement a local fallback:

    $avatarize->setFallback('https://via.placeholder.com/150?text=' . urlencode('No Avatar'));
    

Extension Points

  1. Custom Avatar Services: Replace the default service by implementing Birkof\AvatarizeBundle\Service\AvatarServiceInterface:

    class CustomAvatarService implements AvatarServiceInterface {
        public function generate(string $name, int $size): string {
            return "https://custom-api.com/avatar/$size/$name";
        }
    }
    

    Register it in services.yaml:

    avatarize.service.avatar:
        class: App\Service\CustomAvatarService
        tags: ['avatarize.service']
    
  2. Twig Filters: Extend the Twig extension for project-specific filters:

    // src/Twig/AppExtension.php
    class AppExtension extends \Twig\Extension\AbstractExtension {
        public function getFilters() {
            return [
                new \Twig\TwigFilter('custom_avatar', [$this, 'customAvatar']),
            ];
        }
        public function customAvatar(string $name, int $size = 150) {
            $avatarize = new Avatarize();
            $avatarize->setSize($size);
            return $avatarize->getAvatarUrl($name) . '&theme=monochrome';
        }
    }
    
  3. Event Listeners: Hook into avatar generation for analytics or logging:

    // src/EventListener/AvatarListener.php
    class AvatarListener implements EventSubscriberInterface {
        public static function getSubscribedEvents() {
            return [
                AvatarizeEvents::AVATAR_GENERATED => 'onAvatarGenerated',
            ];
        }
        public function onAvatarGenerated(AvatarEvent $event) {
            \Log::info('Avatar generated for', ['name' => $event->getName(), 'url' => $event->getUrl()]);
        }
    }
    

Configuration Quirks

  • Size Limits: Some avatar services (e.g., adorable.io) cap sizes at 500. Validate sizes in your code:

    $size = min($avatarize->getSize(), 500);
    
  • Case Sensitivity: Initials are case-insensitive by default. Force uppercase if needed:

    $avatarize->setName(strtoupper('john doe')); // "JD"
    
  • Environment-Specific URLs: Use Symfony’s %env% for dynamic base URLs:

    avatarize:
        base_url: '%env(AVATAR_API_URL)%'
    

    Set in .env:

    AVATAR_API_URL=https://custom-avatar-service.com
    
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.
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
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager