I am learning about zf2 events and below is my code:
module.php
public function init(ModuleManagerInterface $managers) {
$eventManager = $managers->getEventManager();
/* $eventManager->attach('do', array($this, function ($e) {
$event = $e->getName();
$params = $e->getParams();
printf(
'Handled event "%s", with parameters %s',
$event,
json_encode($params)
);
})
); */
$eventManager->attach('do', array($this, 'demoEvent') );
}
public function demoEvent(Event $e) {
echo ' in demo Event';
}
and in controller function i have triggered the event.
$this->getEventManager()->trigger('do', $this, ['aman', 'deep']);
but call to demoEvent action is never made. Even i tried using closure as you can see above but it gives me "Invalid callback provided" Exception.
What i am doing wrong. Can someone help me in understanding Event Manager better. Thanks
Your approach is almost correct. The problem is that you are attaching the event listener "demoEvent" to the application event manager, rather than the controller's event manager.
As the controller, assuming that it extends AbstractActionController, will also be capable of triggering it's own events.
You therefore need to update the way you attach the listener to ensure it is registered with the correct event manager.
There are a few options.
Attach event listeners inside the controller factory. You can call $controller->getEventManager()->attach(); inside the factory so when the controller is created the event listener is always attached.
Override the attachDefaultListeners() defined in the AbstractActionController this will automatically be called when the controller is initialized by the controller manager. This provides access to the controllers event manager, just be sure to remember to call parent::attachDefaultListeners().
Lastly, you can use the "Shared Event Manager" which is really just a proxy to the target event manager (and despite its name, not an event manager). This allows you to only slightly modify the code you have written and keep event listener registration independent of the triggering context (controller).
For example.
class Module
{
public function onBootstrap(MvcEvent $mvcEvent)
{
$sharedManager = $mvcEvent->getEventManager()->getSharedManager();
$sharedManager->attach(
'Foo\\Controller\\BarController', // Event manager 'identifier', which one we want
'do' // Name of event to listen to
[$this, 'demoEvent'], // The event listener to trigger
1, // event priority
);
}
public function demoEvent($event)
{
}
}
Related
I've been through the documentation and all the articles on Yii2 events found using Google. Can someone provide me a good example of how events can be used in Yii2 and where it may seem logical?
I can explain events by a simple example. Let's say, you want to do few things when a user first registers to the site like:
Send an email to the admin.
Create a notification.
you name it.
You may try to call a few methods after a user object is successfully saved. Maybe like this:
if($model->save()){
$mailObj->sendNewUserMail($model);
$notification->setNotification($model);
}
So far it may seem fine but what if the number of requirements grows with time? Say 10 things must happen after a user registers himself? Events come handy in situations like this.
Basics of events
Events are composed of the following cycle.
You define an event. Say, new user registration.
You name it in your model. Maybe adding constant in User model. Like const EVENT_NEW_USER='new_user';. This is used to add handlers and to trigger an event.
You define a method that should do something when an event occurs. Sending an email to Admin for example. It must have an $event parameter. We call this method a handler.
You attach that handler to the model using its a method called on(). You can call this method many times you wish - simply you can attach more than one handler to a single event.
You trigger the event by using trigger().
Note that, all the methods mentioned above are part of Component class. Almost all classes in Yii2 have inherited form this class. Yes ActiveRecord too.
Let's code
To solve above mentioned problem we may have User.php model. I'll not write all the code here.
// in User.php i've declared constant that stores event name
const EVENT_NEW_USER = 'new-user';
// say, whenever new user registers, below method will send an email.
public function sendMail($event){
echo 'mail sent to admin';
// you code
}
// one more hanlder.
public function notification($event){
echo 'notification created';
}
One thing to remember here is that you're not bound to create methods in the class that creates an event. You can add any static, non static method from any class.
I need to attach above handlers to the event . The basic way I did is to use AR's init() method. So here is how:
// this should be inside User.php class.
public function init(){
$this->on(self::EVENT_NEW_USER, [$this, 'sendMail']);
$this->on(self::EVENT_NEW_USER, [$this, 'notification']);
// first parameter is the name of the event and second is the handler.
// For handlers I use methods sendMail and notification
// from $this class.
parent::init(); // DON'T Forget to call the parent method.
}
The final thing is to trigger an event. Now you don't need to explicitly call all the required methods as we did before. You can replace it by following:
if($model->save()){
$model->trigger(User::EVENT_NEW_USER);
}
All the handlers will be automatically called.
For "global" events.
Optionally you can create a specialized event class
namespace your\handler\Event\Namespace;
class EventUser extends Event {
const EVENT_NEW_USER = 'new-user';
}
define at least one handler class:
namespace your\handler\Event\Namespace;
class handlerClass{
// public AND static
public static function handleNewUser(EventUser $event)
{
// $event->user contain the "input" object
echo 'mail sent to admin for'. $event->user->username;
}
}
Inside the component part of the config under (in this case) the user component insert you event:
'components' => [
'user' => [
...
'on new-user' => ['your\handler\Event\Namespace\handlerClass', 'handleNewUser'],
],
...
]
Then in your code you can trigger the event:
Yii::$app->user->trigger(EventUser::EVENT_NEW_USER, new EventUser($user));
ADD
You can also use a closure:
allows IDE to "detect" the use of the function (for code navigation)
put some (small) code that manage the event
example:
'components' => [
'user' => [
...
'on new-user' => function($param){ your\handler\Event\Namespace\handlerClass::handleNewUser($param);},
'on increment' => function($param){ \Yii::$app->count += $param->value;},
],
...
]
By default Yii2 already provide some event declaration, You can read more about explanation on BaseActiveRecord.
You can use this variable as same as declaring it manually.
public function init()
{
parent::init();
$this->on(self::EVENT_AFTER_INSERT, [$this, 'exampleMethodHere']);
}
I would like to implement an Event system in my custom MVC framework, to allow decoupling
of classes that need to interact with each other. Basically, the ability for any class to trigger an event and any other class that listens for this event to be able to hook into it.
However, I cannot seem to find a correct implementation given the nature of php's share nothing architecture.
For instance, let's say that I have a User model that each time that it is updated, it triggers a userUpdate event. Now, this event is useful for class A (for instance) as it needs to apply its own logic when a user is updated.
However, class A is not loaded when a user is updated, so it cannot bind to any events triggered by the User object.
How can you get around such a scenario?
Am I approaching it wrongly?
Any ideas would be greatly appreciated
There must be an instance of class A before the event is triggered because you must register for that event. An exception would be if you'd register a static method.
Let's say you have an User class which should trigger an event. First you need an (abstract) event dispatcher class. This kind of event system works like ActionScript3:
abstract class Dispatcher
{
protected $_listeners = array();
public function addEventListener($type, callable $listener)
{
// fill $_listeners array
$this->_listeners[$type][] = $listener;
}
public function dispatchEvent(Event $event)
{
// call all listeners and send the event to the callable's
if ($this->hasEventListener($event->getType())) {
$listeners = $this->_listeners[$event->getType()];
foreach ($listeners as $callable) {
call_user_func($callable, $event);
}
}
}
public function hasEventListener($type)
{
return (isset($this->_listeners[$type]));
}
}
Your User class can now extend that Dispatcher:
class User extends Dispatcher
{
function update()
{
// do your update logic
// trigger the event
$this->dispatchEvent(new Event('User_update'));
}
}
And how to register for that event? Say you have class A with method update.
// non static method
$classA = new A();
$user = new User();
$user->addEventListener('User_update', array($classA, 'update'));
// the method update is static
$user = new User();
$user->addEventListener('User_update', array('A', 'update'));
If you have proper autoloading the static method can be called.
In both cases the Event will be send as parameter to the update method. If you like you can have an abstract Event class, too.
I made a very simple PHP Event Dispatcher / Event Hander for myself, it is testable and has been used on my websites.
If you need it, you can take a look.
Is there a way I can attach an event listener for the event dispatch.error in Zend Framework 2, where that listener will only be attached to an EventManager related to the Module.php?
I have achieved this by attaching listener for dispatch to the global SharedManager and passing the current Module.php's namespace as first param. It works beautifully, but does NOT work, when I try the same for dispatch.error.
Here's an example in Module.php:
public function init(ModuleManager $moduleManager)
{
$sharedManager = $moduleManager->getEventManager()->getSharedManager();
$sharedManager->attach(__NAMESPACE__, 'dispatch', function($e) {
exit('IT WORKS');
});
$sharedManager->attach(__NAMESPACE__, 'dispatch.error', function($e) {
exit('IT DOES NOT WORK');
});
}
The reason it is working for dispatch but not dispatch.error is that the dispatch event gets triggered from within in the controller (see Zend\Mvc\Controller\AbstractController::dispatch)
Because you extend this class with your own namespaced controller, it is possible to associate the event with that namespace.
However, the dispatch.error event may be triggered before a controller (and with it the context of your namespace) is ever loaded. This happens according to more than one condition in Zend\Mvc\DispatchListener.
In order to customize the way dispatch.error is handled, you will likely need to write a custom listener for that event, or even write your own DispatchListener (though I'd recommend against that). You can then perhaps look at the routeMatch to figure out what you'd like to do next. If you're using the ModuleRouteListener this could be pretty easy.
I'm trying to use the Event System in CakePHP v2.1+
It appears to be quite powerful, but the documentation is somewhat vague. Triggering the event seems pretty straight-forward, but I'm not sure how to register the corresponding listener(s) to listen for the event. The relevant section is here and it offers the following example code:
App::uses('CakeEventListener', 'Event');
class UserStatistic implements CakeEventListener {
public function implementedEvents() {
return array(
'Model.Order.afterPlace' => 'updateBuyStatistic',
);
}
public function updateBuyStatistic($event) {
// Code to update statistics
}
}
// Attach the UserStatistic object to the Order's event manager
$statistics = new UserStatistic();
$this->Order->getEventManager()->attach($statistics);
But it does not say where this code should reside. Inside a specific controller? Inside the app controller?
In case it's relevant, the listener will be part of a plugin which I am writing.
Update:
It sounds like a popular way to do this is by placing the listener registration code in the plugin's bootstrap.php file. However, I can't figure out how to call getEventManager() from there because the app's controller classes, etc aren't available.
Update 2:
I'm also told that listeners can live inside Models.
Update 3:
Finally some traction! The following code will successfully log an event when inside of my MyPlugin/Config/bootstrap.php
App::uses('CakeEventManager', 'Event');
App::uses('CakeEventListener', 'Event');
class LegacyWsatListener implements CakeEventListener {
public function implementedEvents() {
return array(
'Controller.Attempt.complete' => 'handleLegacyWsat',
);
}
public static function handleLegacyWsat($event) { //method must be static if used by global EventManager
// Code to update statistics
error_log('event from bootstrap');
}
}
CakeEventManager::instance()->attach(array('LegacyWsatListener', 'handleLegacyWsat'), 'Controller.Attempt.complete');
I'm not sure why, but I can't get errors when I try to combine the two App::uses() into a single line.
Events
Events are callbacks that are associated to a string. An object, like a Model will trigger an event using a string even if nothing is listening for that event.
CakePHP comes pre-built with internal events for things like Models. You can attach an event listener to a Model and respond to a Model.beforeSave event.
The EventManager
Every Model in Cake has it's own EventManager, plus there is a gobal singleton EventManager. These are not all the same instance of EventManager, and they work slightly differently.
When a Model fires an event it does so using the EventManager reference it has. This means, you can attach an event listener to a specific Model. The advantages are that your listener will only receive events from that Model.
Global listeners are ones attached to the singleton instance of EventManager. Which can be accessed anywhere in your code. When you attach a listener there it's called for every event that happens no matter who triggers it.
When you attach event listener in the bootstrap.php of an app or plugin, then you can use the global manager, else you have to get a reference to the Model you need using ClassRegistry.
What EventManager To Use?
If the event you want to handle is for a specific Model, then attach the listener to that Model's EventManager. To get a reference of the model you can call the ClassRegistry::init(...).
If the event you want to handle could be triggered anywhere, then attach the listener to the global EventManager.
Only you know how your listener should be used.
Inside A Listener
Generally, you put your business logic into models. You shouldn't need to access a Controller from an event listener. Model's are much easier to access and use in Cake.
Here is a template for creating a CakeEventListener. The listener is responsible for monitoring when something happens, and then passing that information along to another Model. You should place your business logic for processing the event in Models.
<?php
App::uses('CakeEventListener', 'Event');
class MyListener implements CakeEventListener
{
/**
*
* #var Document The model.
*/
protected $Document;
/**
* Constructor
*/
public function __construct()
{
// get a reference to a Model that we'll use
$this->Document = ClassRegistry::init('Agg.Document');
}
/**
* Register the handlers.
*
* #see CakeEventListener::implementedEvents()
*/
public function implementedEvents()
{
return array(
'Model.User.afterSave'=>'UserChanged'
);
}
/**
* Use the Event to dispatch the work to a Model.
*
* #param CakeEvent $event
* The event object and data.
*/
public function UserChanged(CakeEvent $event)
{
$data = $event->data;
$subject = $event->subject();
$this->Document->SomethingImportantHappened($data,$subject);
}
}
What I like to do is place all my Events into the Lib folder. This makes it very easy to access from anywhere in the source code. The above code would go into App/Lib/Event/MyListener.php.
Attaching The EventListeners
Again, it depends on what events you need to listen for. The first thing you have to understand is that an object must be created in order to fire the event.
For example;
It's not possible for the Document model to fire Model.beforeSave event when the Calendar controller is displaying an index, because the Calendar controller never uses the Document model. Do you need to add a listener to Document in the bootstrap.php to catch when it saves? No, if Document model is only used from the Documents controller, then you only need to attach the listener there.
On the other hand, the User model is used by the Auth component almost every. If you want to handle a User being deleted. You might have to attach an event listener in the bootstrap.php to ensure no deletes sneak by you.
In the above example we can attach directly to the User model like so.
App::uses('MyListener','Lib');
$user = ClassRegistry::init('App.User');
$user->getEventManager()->attach(new MyListener());
This line will import your listener class.
App::uses('MyListener','Lib');
This line will get an instance of the User Model.
$user = ClassRegistry::init('App.User');
This line creates a listener, and attaches it to the User model.
$user->getEventManager()->attach(new MyListener());
If the User Model is used in many different places. You might have to do this in the bootstrap.php, but if it's only used by one controller. You can place that code in the beforeFilter or at the top of the PHP file.
What About Global EventManager?
Assuming we need to listen for general events. Like when ever any thing is saved. We would want to attach to the global EventManager. It would go something like this, and be placed in the bootstrap.php.
App::uses('MyListener','Lib');
CakeEventManager::instance()->attach(new MyListener());
If you want to attach an event listener inside bootstrap.php file of your plugin, everything should work fine using the hints posted in the answers. Here is my code (which works properly):
MyPlugin/Config/bootstrap.php:
App::uses('CakeEventManager', 'Event');
App::uses('MyEventListener', 'MyPlugin.Lib/Event');
CakeEventManager::instance()->attach(new MyEventListener());
MyPlugin/Lib/Event/MyEventListener.php:
App::uses('CakeEventListener', 'Event');
class MyEventListener implements CakeEventListener {
...
}
Event listeners related to MyPlugin are being registered only when the plugin is loaded. If I don't want to use the plugin, event listeners are not attached. I think this is a clean solution when you want to add some functionality in various places in your app using a plugin.
Its' not important, where the code resides. Just make sure its being executed and your events are properly registered & attached.
We're using a single file where all events are attached and include it from bootstrap.php, this ensures that all events are available from all locations in the app.
The magic happens when you dispatch an event, like from an controller action.
$event = new CakeEvent('Model.Order.afterPlace', $this, array('some'=>'data') ));
$this->getEventManager()->dispatch($event);
However, you can dispatch events from anywhere you can reach the EventManager (in Models, Controller and Views by default)
I'm trying to configure the finish function for module.php in zend, from what I understand you need to configure some sort of listener (in bootstrap I think) that will call the finish function and I can then execute code after its finished with the user request.
Can someone provide some example code to setup the module to call finish once it has finished the user request.
Thanks!
You can do this in the onBootstrap method of your Module.php as the following:
public function onBootstrap(MvcEvent $e)
{
$em = $e->getApplication()->getEventManager();
$em->attach(\Zend\Mvc\MvcEvent::EVENT_FINISH, array($this, 'doSomething'));
}
and then define a function that doSomething in your Module.php as the following:
public function doSomething(MvcEvent $e)
{
// your code goes here
}
You can also add some priority for the callback functions you want to execute if you attached more than one listener on the same event as the following:
$em->attach(\Zend\Mvc\MvcEvent::EVENT_FINISH, array($this, 'doSomethingFirst'), 20);
$em->attach(\Zend\Mvc\MvcEvent::EVENT_FINISH, array($this, 'doAnotherThingLater'), 10);
Higher priority values execute earliest. (Default priority is 1, and negative priorities are allowed.)
The basic idea is to attach a listener to the event, as you've rightly noted the place to do that is in the onBootstrap method of your Module class. The following should get you started...
public function onBootstrap(MvcEvent $e)
{
$e->getApplication()->getEventManager()->attach(MvcEvent::EVENT_FINISH, function ($e) {
// do something...
});
}