Zend Basic Tutorial
Zend Forms
Zend Database
Zend Advanced
Zend EventManager is a publish-subscribe system — it allows different parts of your app to communicate without being tightly coupled.
Like:
🧱 “When a user registers, also send a welcome email and log the action.”
👉 These are all events and listeners.
composer require laminas/laminas-eventmanager
2. Create Event Manager, Attach Listener and Trigger the Event (module\Application\src\Controller\MainController.php)
use Laminas\EventManager\EventManager;
class MainController extends AbstractActionController
{
protected $eventManager;
public function __construct()
{
$this->eventManager = new EventManager();
$this->eventManager->attach('user.register', function($e) {
echo "User Registered: " . $e->getParam('name');
});
}
public function homeAction()
{
$this->eventManager->trigger('user.register', null, ['name' => 'John']);
return new ViewModel();
}
}
Output:
User Registered: John
use Laminas\EventManager\Event;
use Laminas\EventManager\EventManager;
class MainController extends AbstractActionController
{
protected $eventManager;
public function __construct()
{
$this->eventManager = new EventManager();
$this->eventManager->attach('user.register', function($e) {
echo "User Registered: " . $e->getParam('name');
});
}
public function homeAction()
{
$event = new Event();
$event->setName('order.register');
$event->setParams(['name' => 'Sathish']);
return new ViewModel();
}
}
Module.php (module\Application\src\Module.php):use Laminas\Mvc\MvcEvent;
use Application\Controller\MainController;
class Module
{
public function getConfig(): array
{
/** @var array $config */
$config = include __DIR__ . '/../config/module.config.php';
return $config;
}
public function onBootstrap(MvcEvent $e)
{
$sharedManager = $e->getApplication()->getEventManager()->getSharedManager();
$sharedManager->attach(
'MainController', // Controller class name
'user.register', // Event name
function ($e) {
$params = $e->getParams();
echo "✅ Global Event: User registered with email " . $params['email'] . "<br>";
}
);
}
}
class MainController extends AbstractActionController
{
public function homeAction()
{
$this->getEventManager()->trigger('user.register', $this, [
'email' => 'user@example.com',
]);
return new ViewModel();
}
}
If you want to attach event listener globally, do it in Module.php:
public function onBootstrap(MvcEvent $e)
{
$sharedManager = $e->getApplication()->getEventManager()->getSharedManager();
$sharedManager->attach(
'*', // Listen globally to user.login
'user.register', // Event name
function ($e) {
$params = $e->getParams();
echo "✅ Global Event: User registered with email " . $params['email'] . "<br>";
}
);
}
The Event Manager is ideal for managing:
|
Use Case |
Example Class |
Purpose (When/Why) |
|---|---|---|
|
User Registration |
|
Fire |
|
Order Placed |
|
Fire |
|
Login Auditing |
|
Trigger |
|
Payment Success |
|
Trigger |