I am developing a web application using Laravel framework. I am trying to trying to use event and listener in my application. But the event was trigged and the listener for the trigged event is not fired.
This is my controller action
public function store(Request $request)
{
//other code
$item = Item::create($request->all())
broadcast(new ItemCreated($item));
return "Item created successfully";
}
This is my Events\ItemCreated.php
class ItemCreated
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $item;
public function __construct($item)
{
$this->item = $item;
}
}
Then I have a listener for that event.
Listeners/EmailSubscribedUsers.php
class EmailSubscribedUsers
{
public function __construct()
{
//this constructor is not triggered
}
public function handle(ItemCreated $event)
{
//This method is not fired
}
}
In the EventServiceProvider I registered the event and the listener like this
protected $listen = [
ItemCreated::class => [
EmailSubscribedUsers::class
]
];
The event is trigged. But the listener is not fired. Why? What is wrong?
I tried the following solutions.
php artisan optimize
composer dumpautoload
php artisan clear-compiled
Sorry everyone. The issue was I was unit testing. In the unit testing if I used Event::fake(), the event listeners are not triggered. I wanted to tested the logic in the event listeners. Therefore, I removed the Event::fake() and tested the logic in the listener instead.
First of all as pointed in comments use
event(new ItemCreated($item));
and not
broadcast(new ItemCreated($item));
In addition make sure you have set QUEUE_CONNECTION to sync in your .env file. If you used some other connection (for example database or Redis) make sure you run in console command:
php artisan queue:work
The last thing - verify your error log in storage/logs directory. You might have some other errors (for example missing import) and that's why your listener fails.
Also make sure in EventServiceProvider that you use valid classes and imported valid namespaces - otherwise listener won't be triggered.
In an application I am working, I've both Job and Event Listener implemented Should Queue. In the queue, I perform a database insert and I want after the queue complete, I want to remove the previous cache. So I use Queue Job Event like this example:
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Queue::after(function (JobProcessed $event) {
Log::info('[QUEUE COMPLETE]', $event->job->getName());
});
}
public function register()
{
//
}
}
But the event is never fired and there is no log found in storage/log folder. I use daily logging channel.
Why is it not logging?
Answering my own question after solving this.
All the code is fine, I just needed to stop the queue:work and start it again (restart). After this, the Queue::after event started to fire and all worked perfectly.
I created an Event \ Listener by registering the pair in the EventServiceProvider.
After running php artisan generate:event Laravel creates the Event and Listener classes in there respected directories.
I notice that if you want to fire an event you need to call the static Event::fire method.
Event::fire( new SomeEventClass($variable));
However I noticed that if you wanted to pass a $variable into the Listener.
You would need to declare $variable as a public property of the class and create a constructor in the Associated Event class so that you can use it in the Listener class, by later passing $variable from $event->variable, otherwise $variable would not work in the Listener class.
class SomeEventClass extends Event {
use SerializesModels;
public $variable;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct($variable) {
$this->variable = $variable;
}
/**
* Get the channels the event should be broadcast on.
*
* #return array
*/
public function broadcastOn() {
return [];
}
}
So to re-clarify my question what is "going on under the hood" in this situation.
I don't think there is a lot going on under the hood here, it's a pretty transparent process.
When you fire an event, Laravel will look up all the listeners for that event (via the array in the EventServiceProvider class) and pass the event class to each listener it finds and call the handle method on each listener.
The event class really only does one thing, it holds onto the data for the listeners to eventually use. We set that data to public because that creates a very simple way for the listeners to pull the data they need out of the event class.
Pls I'm still new to laravel and I have used events in laravel a couple of times but I'm curious and would like to know if it's possible to execute an event in laravel asynchronously. Like for instance in the code below:
<?php
namespace mazee\Http\Controllers;
class maincontroller extends Controller
{
public function index(){
Event::fire(new newaccountcreated($user)) ;
//do something
}
Is it possible for the block of code in the event listener of the "newaccountcreated" event to be executed asynchronously after the event is fired ?
Yes of course this is possible. You should read about Laravel Queues. Every driver (only not sync driver) are async. The easiest to configure is the database driver, but you can also want to try RabbitMQ server , here is Laravel bundle for it.
You can also add to your EventListener: newaccountcreated trait Illuminate\Queue\InteractsWithQueue (you can read about him here) which will helps you to connect it with Laravel Queue.
Filip's answer covers it all. I will add a bit more to it. If you push an event it will goto the default queue. You can specify a queue name as well. Have the listener class implements ShouldQueue and just include the queue method in the listener class like below.
/**
* Push a new job onto the queue.
**/
public function queue($queue, $job, $data)
{
return $queue->pushOn('queue-name', $job, $data);
}
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)