Skip to content
  • Homepage
  • HTML
  • CSS
  • Symfony
  • PHP
  • How to
  • Contact
  • Donate

Teach Developer

Articles, Guides & Tips

How to use events listeners and Event Subscriber in Symfony

Home  »  How to • PHP • Symfony • Top Tutorials   »   How to use events listeners and Event Subscriber in Symfony
Posted on July 21, 2023July 21, 2023
805

We use events to perform some tasks if an event occurs, these tasks can be achieved by using the followings:

1. Event Subscriber

2. Event Listeners

Event Subscriber vs Event Listeners

They both serve the same purpose but have different implementations. Both trigger some functions in the specific time of processing data by Symfony.

We can declare multiple functions inside an event subscriber and set the priorities of the functions in the order in which each function will be called. Still, it can’t be achieved in event listeners, so internally Symfony also uses event subscribers over event listeners.

1. Event Subscriber

It is declared as follows:

// src/EventSubscriber/ExceptionSubscriber.php
namespace App\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class ExceptionSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::EXCEPTION => [
                ['handleException', 1],
                ['notifyAdminUser', 2],
            ],
        ];
    }

    public function handleException(ExceptionEvent $event)
    {
        // ...
    }

    public function notifyAdminUser(ExceptionEvent $event)
    {
        // ...
    }
}

This event subscriber handles the kernel exceptions like when we do not define routes in our project then this subscriber will be called. Also, we need to register this subscriber in the config/services.yml file.

App\EventSubscriber\ExceptionSubscriber:
    tags:
        - {doctrine.event_subscriber, connection: default}

The subscriber function with the high number set as priority will be called first and the subscriber function with the lower number set as priority will be called last. Here the function notifyAdminUser will be called and then the function handleException will be called.

2. Event Listener

As explained above the event listener is used for the same reason. It is declared as follows:

// src/EventListener/ExceptionListener.php
namespace App\EventListener;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;

class ExceptionListener
{
    public function onKernelException(ExceptionEvent $event)
    {
        $exception = $event->getThrowable();
        $message = sprintf(
            'Getting following error: %s with code: %s',
            $exception->getMessage(),
            $exception->getCode()
        );

        // Customize your response object to display the exception details
        $response = new Response();
        $response->setContent($message);

        // HttpExceptionInterface is a special type of exception that
        // holds status code and header details
        if ($exception instanceof HttpExceptionInterface) {
            $response->setStatusCode($exception->getStatusCode());
            $response->headers->replace($exception->getHeaders());
        } else {
            $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
        }

        // sends the modified response object to the event
        $event->setResponse($response);
    }
}

This listener will be called once a kernel exception occurs like calling a route that does not exist. In this case, this listener will be called to handle the exception. Also, we need to register this listener in the config/services.yml file.

services:
    App\EventListener\ExceptionListener:
        tags:
            - { name: kernel.event_listener, event: kernel.exception }

Thanks for reading me. I hope this blog would help you with a better understanding of Symfony subscribers and listeners.

How to, PHP, Symfony, Top Tutorials

Post navigation

Previous Post: How to Convert PHP CSV to JSON
Next Post: How to Deploy a React application on a cPanel

Related Posts

  • How to make the scrollbar visible in mobile browsers with CSS?
  • How to PHP Get Max Value From Array
  • How to make the div move up and down when scrolling the page with CSS?
  • How to change background Opacity when the bootstrap modal is open with CSS?
  • How to install Git on Linux
  • How to Change SSH Port in Linux

Categories

  • Codeigniter (3)
  • CSS (11)
  • eCommerce (1)
  • Framework (1)
  • Git (3)
  • How to (43)
  • HTML (5)
  • JavaScript (15)
  • Jquery (7)
  • Laravel (1)
  • Linux (4)
  • Magento-2 (1)
  • Node js (4)
  • Others (2)
  • PHP (11)
  • React (13)
  • Server (1)
  • SSH (3)
  • Symfony (6)
  • Tips (16)
  • Top Tutorials (10)
  • Ubuntu (3)
  • Vue (1)
  • Wordpress (7)

Latest Posts

  • What is SSH in Linux?
  • How to Delete Files in Ubuntu Command Line
  • How to Deploy a React application on a cPanel
  • How to use events listeners and Event Subscriber in Symfony
  • How to Convert PHP CSV to JSON

WEEKLY TAGS

AJAX (1) Codeigniter (1) Javascript (11) JQuery (1) PHP (16) Programming (1) React (3) Symfony (1)

Random Post

Difference between var, let, and const in JavaScript
PHP 8.1: read-only properties
How to split a string into an array with Twig
How to Install a WordPress Plugin for Beginners
How to trigger a button click from another button click event with JavaScript?

Quick Navigation

  • About
  • Contact
  • Privacy Policy

© Teach Developer 2021. All rights reserved