Lets start with a small explanation. Gravatars are so called ‘globally recognized avatars’. Basically it is an open directory for avatars. If you didn’t get one yet, feel free to head over to www.gravatar.com.
The implementation of gravatars for your site is already extremely easy. However if you are fortunate enough to be using Symfony, it becomes a real piece of cake. Quite a few people already use gravatars, including the Symfony blog. This number will probably increase quite a bit, given the recent purchase of the company by Automattic.
Gravatars are attached to an email address. Lets assume your program is already setting and getting the email addresses. All you need to get up and running with Gravatars is these simple 3 steps.
1. Extend your setEmail to do setGravatar as well
(somewhere in lib/Comment.php)
function setEmail($input) {
$this->setGravatar(md5($input));
parent::setEmail($input);
}
2. When getting the Gravatar, retrieve the full image code
(somewhere in lib/Comment.php)
function getGravatar() {
$md5email = parent::getGravatar();
$size = 45;
$rating = 'R'; // possible values [ G | PG | R | X ]
$url = '<img width='.$size.'px height='.$size.'px class="gravatar" src="http://www.gravatar.com/avatar.php?gravatar_id='.$md5email.'&rating='.$rating.'&size=35" alt="gravatar" />';
return $url;
}
3. In your view template
Simply do: $comment->getGravatar();
DONE!
Have a look at the result:







Stefan responded on 19 Oct 2007 at 6:46 pm #
Excellent, though I was doing real-time md5-ing. I guess it’s a matter of choice, since saving redundant data in your database is not good according to normalization, but doing md5-stuff on every request is maybe also not good.
tschellenbach responded on 19 Oct 2007 at 7:11 pm #
Actually I was in doubt. I am not sure how heavy the md5 function is. Didn’t want to risk it :)
Stefan responded on 20 Oct 2007 at 2:26 pm #
heh. well, md5 is a pretty basic algorhythm I think. but each function call of course has it’s cost. then again, you’ll always use a function call, be it md5, be it a getter.
ah well, I think in this case there’s little to be won in whatever direction.
rpsblog.com » A week of symfony #42 (15->21 October 2007) responded on 21 Oct 2007 at 9:18 pm #
[...] Symfony & Gravatars – easy implementation [...]
Symfony.es » Blog Archive » Una semana con Symfony #15 (15-21 Octubre 2007) responded on 03 Dec 2007 at 9:34 am #
[...] Symfony & Gravatars – easy implementation [...]