PHP Symfony - example how to use Event, EventListener and EventDispatcher

PHP Symfony - example how to use Event, EventListener and EventDispatcher

Hello,

I have trouble understanding how to use PHP Symfony Event, EventListener and EventDispatcher in PHP. What is in the documentation refers to the kernel, etc., and that doesn't make much sense to me. I have no idea how to use it to just print a message that EventListener would print via echo.

Thanks

REPLY


Hi,

here is a practical example of using Event, EventListener and EventDispatcher in the Symfony framework:


CONTROLLER
-----------------------------------------------------

...........
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Contracts\EventDispatcher\Event;
use App\Event\DemoEvent;
use App\EventListener\DemoListener;
.............
$dispatcher = new EventDispatcher();
$listener = new DemoListener();
$dispatcher->addListener('demo.created', array($listener, 'onDemoEvent'));
$dispatcher->dispatch(new DemoEvent(), 'demo.created');
.............



EVENT
Event/DemoEvent.php
-----------------------------------------------------

namespace App\Event;

use App\Entity\Demo;
use Symfony\Contracts\EventDispatcher\Event;

class DemoEvent extends Event
{
protected $var;

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

public function getVar()
{
return $this->var;
}
}



EVENT LISTENER
EventLister/DemoListener.php
-----------------------------------------------------

namespace App\EventListener;

use Symfony\Contracts\EventDispatcher\Event;

class DemoListener
{
public function onDemoEvent(Event $event)
{
echo "Byl zavolan DemoListener - hodnota je: ".$event->getVar();
}
}




The output for $dispatcher->dispatch(new DemoEvent(), 'demo.created'); is:

Byl zavolan DemoListener - hodnota je: string


PS: 100% funkční oveřené

Související obsah

programovani

symfony

php

event

Komentáře

Vaše reakce na PHP Symfony - příklad jak použít Event, EventListener a EventDispatcher

Reference

Podívejte se na naše reference

Prohlédnout

Aplikace

Podívejte se na naše aplikace

Prohlédnout

Co umíme?

Podívejte se co umíme

Prohlédnout

Co umíme?

Vytváříme sofistikované aplikace pro náročné

Od webových aplikací přes android až po převodové můstky či složité informační systémy.

Podívejte se k nám

Máte ještě čas? Podívejte se na další rubriky

Tento web používá soubory cookie. Dalším procházením tohoto webu vyjadřujete souhlas s jejich používáním.. Více informací zde.