2

I'm using the symfony/event-dispatcher component and am trying to get a 'hello world' thing to work, I think.

My application (not symfony2) runs bootstrap.php then MVC's its way to some file I named composer.php.

bootstrap.php (the necessary parts)

<?php
require __DIR__ . '/vendor/autoload.php';

use Events\MsgEvent;
use Symfony\Component\EventDispatcher\EventDispatcher;
$dispatcher = new EventDispatcher();

if ($user_id) {
    $dispatcher->dispatch('msg_event', new MsgEvent("I'm logged in as: " . $user['username']));
}

composer.php

<?php
use Events\MsgEvent;

$dispatcher->addListener('msg_event', function (MsgEvent $event) {
    echo $event->getMsg();
});

$dispatcher->dispatch('msg_event', new MsgEvent("I got called from composer.php"));

On the route for my composer.php page I get to see 'called from composer', but my 'logged in as' message doesn't appear. When I output it's return, I can see it has succesfully created the event.

I have a feeling the problem is that the listener is defined after the first dispatch and somehow this does not get stored in the dispatcher. But I'm not sure.

What am I not seeing here?

2
  • Where is comport.php included?
    – Gerry
    Commented Aug 18, 2015 at 19:05
  • index.php includes bootstrap.php which gives a $controller, then layout.php gets included and in there there's a call to $controller->page which will include the final view/composer.php Commented Aug 18, 2015 at 19:16

1 Answer 1

2

You are dispatching the event before registering a listener. Since bootstrap.php is included before composer.php, the first event will fire with no listeners attached to it.

2
  • So that's intended behaviour? Commented Aug 19, 2015 at 8:51
  • Definitely. Dispatching is immediate, so when you dispatch the first event it will fire with nothing listening. The event dispatcher is not a message queue, which I think you are confusing it with.
    – Gerry
    Commented Aug 19, 2015 at 9:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.