I am wondering where to put the Laravel Event Listeners and Handlers. Somebody told me that I can put them anywhere. This is what I have tried so far.
# listeners/log.php
<?php
Event::listen('log.create', 'LogHandler@create');
# handlers/LogHandler.php
<?php
class LogHandler {
public function create(){
$character = new Character;
$character->name = "test";
$character->save();
}
}
# controllers/MainController.php
public function test(){
Event::fire('log.create');
return "fired";
}
# start/global.php
ClassLoader::addDirectories(array(
app_path().'/commands',
app_path().'/controllers',
app_path().'/models',
app_path().'/database/seeds',
app_path().'/libraries',
app_path().'/listeners',
app_path().'/handlers',
));
We can put the event handling code into one of the following places: Within class. Other class. Anonymous class.
Its stored in the actual list (array) of Event listeners for body . Elements have a list of function references in them for their event listeners. These references are not in the DOM. When firing an event, the browser has to run thru all the appropriate elements looking for these references and running them in order.
Note: Event handlers are sometimes called event listeners — they are pretty much interchangeable for our purposes, although strictly speaking, they work together. The listener listens out for the event happening, and the handler is the code that is run in response to it happening.
I'm going to assume that you're asking this because they're not working, rather than for confirmation of something that you've got working.
Whilst it is correct that you can put event listeners anywhere, you need to make sure they'll actually get included - Laravel doesn't search through your source code looking for them.
My favourite place to include such files is in start/global.php
. If you look at the bottom of the file you can see where the filters are included, you can do the same to include your listeners. It would be cleanest to keep them all in one listeners file, like all of your routes are in one routes file...
# start/global.php
require app_path().'/filters.php';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With