Skip to content

Instantly share code, notes, and snippets.

@rodrigodiez
Last active December 20, 2015 15:39
Show Gist options
  • Select an option

  • Save rodrigodiez/6155772 to your computer and use it in GitHub Desktop.

Select an option

Save rodrigodiez/6155772 to your computer and use it in GitHub Desktop.
Example of flood control using REDIS (Predis vía Symfony SNCRedisBundle)
<?php
namespace Foo/Bar/Event/Observer/CommentSubscriber;
// ...
// Use statements, constructor, boring code...
// ...
// Our callable wich listen for new comment attempt
public function onNewComment(FilterCommentEvent $event)
{
$comment = $event->getComment();
$user = $comment->getUser();
// ...
// If there are more than 10 living keys then the user is trying to flood us
if(count($this->redisClient->keys('user:' . $user->getId() ':comments:attempt:*')) > 10)
{
throw new \Exception('Comments limit reached');
}
}
<?php
namespace Foo/Bar/Model/Manager;
// ...
// Use statements, constructor, boring code...
// ...
// Our callable wich saves a new comment
public function save(Comment $comment)
{
$event = new CommentEvent();
$event->setComment($comment);
// Raise our event
$this->dispatcher->dispatch('foo.bar.comment.new',$event);
// ...
// We save our comment at db
// ...
// We register the comment attempt with a unique key and a foo value. It will expire
// after 300 seconds (5 minutes)
$redisKey = 'user:' . $comment->getUser()->getId() . ':comments:attempt:' . uniqid();
$this->redisClient->set($redisKey,'foo');
$this->redisClient->expire($redisKey,300);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment