Installation:
composer require birkof/avatarize
Ensure your composer.json includes "birkof/avatarize": "^0.2" (or latest stable).
Enable the Bundle (Symfony 4+):
Add to config/bundles.php:
return [
// ...
Birkof\AvatarizeBundle\AvatarizeBundle::class => ['all' => true],
];
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"
Check config/packages/avatarize.yaml (auto-generated) for default settings like:
https://api.adorable.io/avatars/)285)Generating Avatars:
$avatarize->getAvatarUrl('Elon Musk'); // "https://api.adorable.io/avatars/285/em.png"
$avatarize->setSize(150)->getAvatarUrl('Jane Smith'); // "https://api.adorable.io/avatars/150/js.png"
$avatarize->getAvatarUrl('🚀 Rocket'); // Handles non-ASCII characters
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">
Dynamic Fallbacks: Override default behavior (e.g., for empty names):
$avatarize->setFallback('?default=1'); // Appends to URL
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"
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/'
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).
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.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.
Invalid URLs: Log the raw URL before generation to debug:
$url = $avatarize->getAvatarUrl('Test User');
\Log::debug('Generated URL:', ['url' => $url]);
Common issues:
285).& 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'));
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']
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';
}
}
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()]);
}
}
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
How can I help you explore Laravel packages today?