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
Hi,
here is a practical example of using Event, EventListener and EventDispatcher in the Symfony framework:
CONTROLLER
-----------------------------------------------------
EVENT
Event/DemoEvent.php
-----------------------------------------------------
EVENT LISTENER
EventLister/DemoListener.php
-----------------------------------------------------
The output for
PS: 100% funkční oveřené
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é