Skip to content

Instantly share code, notes, and snippets.

@bhaktaraz
Last active November 7, 2020 15:16
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bhaktaraz/cb6837b9b452e8a9ea3f to your computer and use it in GitHub Desktop.
Save bhaktaraz/cb6837b9b452e8a9ea3f to your computer and use it in GitHub Desktop.
Symfony Event Listener to Increase Post View Count
<?php
/**
* Created by PhpStorm.
* User: bhaktaraz
* Date: 8/24/15
* Time: 9:51 AM
*/
namespace BRB\Bundle\PostBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class PostController extends Controller
{
public function viewAction()
{
$event = new PostEvent($post);
$dispatcher = $this->get('event_dispatcher');
$dispatcher->dispatch(
PostEvents::POST_VIEWED,
$event
);
}
}
<?php
/**
* Created by PhpStorm.
* User: bhaktaraz
* Date: 11/16/15
* Time: 11:14 AM
*/
namespace BRB\Bundle\ApiBundle\Event;
use BRB\Bundle\PostBundle\Entity\Post;
use Symfony\Component\EventDispatcher\Event;
class PostEvent extends Event
{
protected $post;
public function __construct(Post $post)
{
$this->post = $post;
}
public function getPost()
{
return $this->post;
}
}
<?php
/**
* Created by PhpStorm.
* User: bhaktaraz
* Date: 11/16/15
* Time: 11:14 AM
*/
namespace BRB\Bundle\ApiBundle\Event;
final class PostEvents
{
const POST_VIEWED = 'post.viewed';
}
<?php
/**
* Created by PhpStorm.
* User: bhaktaraz
* Date: 11/16/15
* Time: 11:23 AM
*/
namespace BRB\Bundle\ApiBundle\Listener;
use BRB\Bundle\ApiBundle\Event\PostEvent;
use Doctrine\ORM\EntityManager;
class PostListener
{
/**
*
* @var EntityManager
*/
protected $em;
public function __construct(EntityManager $entityManager)
{
$this->em = $entityManager;
}
public function onPostViewed(PostEvent $event)
{
$post = $event->getPost();
$post->increaseViewCount(); // This method shoud be in your Post entity
$this->em->persist($post);
$this->em->flush();
}
}
services:
post_bundle.listener.post:
class: BRB\Bundle\ApiBundle\Listener\PostListener
arguments: [ "@doctrine.orm.entity_manager" ]
tags:
- { name: kernel.event_listener, event: post.viewed, method: onPostViewed }
@gulaandrij
Copy link

👎

@aminkhoshzahmat
Copy link

@gulaandrij Do you have better solution?

@bhaktaraz
Copy link
Author

@gulaandrij In this gist I'm just trying to illustrate how event listeners work. It may not be the right way for view count.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment