Last active
December 20, 2015 15:39
-
-
Save rodrigodiez/6155772 to your computer and use it in GitHub Desktop.
Example of flood control using REDIS (Predis vía Symfony SNCRedisBundle)
Raw
CommentListener.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Show hidden characters
| <?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'); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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