Symfony Event Dispatcher alias the pattern observer

RemySd
2 min readNov 6, 2023

--

One of my favorite pattern, er, my favorite. I would like to talk to you about this pattern and how it is implemented with Symfony.

How works the observer pattern? Imagine this pattern like a real-world situation, you are 3 boy’s and you talk about the new Gen V show! Only one person have watch the show and explain why two others need to show him too. This person is the emitter (or dispatcher), he spreads informations. The others are observers (or listeners), they listening to, and they can interacting if they want. between these 2 roles (emitter and observers), we have the event, this the voice in this case.

Well, after this briefing, let’s see how the code is implemented!

If you want to try this code, you should install symfony/event-dispatcher with composer before to test

index.php

<?php

require_once dirname(__DIR__) . '/vendor/autoload.php';

use App\Event\VoiceEvent;
use App\EventSubscriber\VoiceSubscriber;
use Symfony\Component\EventDispatcher\EventDispatcher;

$dispatcher = new EventDispatcher();

$subscriber1 = new VoiceSubscriber();
$subscriber2 = new VoiceSubscriber();
$dispatcher->addListener('event.blabla', [$subscriber1, 'doSomething']);
$dispatcher->addListener('event.blabla', [$subscriber2, 'doSomethingElse']);

$event = new VoiceEvent('bla bla bla');

$dispatcher->dispatch($event, 'event.blabla');

This is the first script run. I have created a $dispatcher and associate two listeners to it. After that, I create two subscribers, for they two peoples who listen the speaker. The VoiceEvent is merely the dialog than the speaker say. Finally, we dispatch this EventVoice, the two subscribers can interact if they want.

VoiceSubscriber.php

<?php

namespace App\EventSubscriber;

use App\Event\VoiceEvent;

class VoiceSubscriber
{
public function doSomething(VoiceEvent $voiceEvent): void
{
// scratch your hair
}

public function doSomethingElse(VoiceEvent $voiceEvent): void
{
// scratch your nose
}
}

Here is the action made by listener, there functions are specified in the index.php

VoiceEvent.php

<?php

namespace App\Event;

use Symfony\Contracts\EventDispatcher\Event;

class VoiceEvent extends Event
{
private string $message;

public function __construct(string $message)
{
$this->message = $message;
}

public function getMessage(): string
{
return $this->message;
}
}

The event which contains than the speaker say in the $message property.

This code implementation is very useful when you want to decoupled your code in multiple parts. You can have a more maintainable code and you don’t lock your futur implementations with the modularity. You know, like an independent freelance, you are not strongly link to another things.

--

--