我正在关注一本书,它展示了如何触发一个新事件并开始监听它。该事件称为通道 25,它仅包含用于测试的虚构数据。我将 error_log 用于捕获事件过程,以便我知道它的工作原理。该事件确实被触发,但由于某种原因我无法听它。这是module.php的副本
我已经评论了我触发事件的地方以及我在哪里听它的部分。
<?php
namespace Debug;
use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\Mvc\ModuleRouteListener;
use Zend\ModuleManager\ModuleManager;
use Zend\eventManager\Event;
use Zend\Mvc\MvcEvent;
use Zend\EventManager\EventManager; //manage events (create/listen for events)
class Module implements AutoloaderProviderInterface
{
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
public function init(ModuleManager $ModuleManager)
{
$eventManager = $ModuleManager->getEventManager();
$eventManager->attach('loadModules.post', array($this, 'loadedModulesInfo'));
//create new event
$event = new EventManager('channel-25');
$event->trigger('new song', null, array('artist' => 'Adele'));
error_log('New Event Triggered');
}
public function loadedModulesInfo(Event $event)
{
$moduleManager = $event->getTarget();
$loadedModules = $moduleManager->getLoadedModules();
error_log(var_export($loadedModules, true));
}
public function onBootstrap(MvcEvent $event)
{
//Now i will be listening for my sample event
$eventManager = $event->getApplication()->getEventManager();
$sharedEventManager = $eventManager->getSharedManager();
$sharedEventManager->attach('channel-25', 'new song', function(Event $event) {
$artist = $event->getParam('artist');
error_log('Found the Event. The artist is: ' . $artist);
});
}
public function handleError(MvcEvent $event)
{
$controller = $event->getController();
$error = $event->getParam('error');
$exception = $event->getParam('exception');
$message = 'Error: ' . $error;
if($exception instanceof \Exception)
{
$message .= ', Exception(' . $exception->getMessage() . '):' . $exception->getTraceAsString();
}
error_log($message);
}
}