Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@gulaandrij gulaandrij commented Sep 20, 2018

👎

@aminkhoshzahmat

This comment has been minimized.

Copy link

@aminkhoshzahmat aminkhoshzahmat commented Nov 5, 2020

@gulaandrij Do you have better solution?

@bhaktaraz

This comment has been minimized.

Copy link
Owner Author

@bhaktaraz bhaktaraz commented Nov 7, 2020

@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