Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where do I put event listeners and handlers?

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',
));
like image 331
Bernd Strehl Avatar asked Apr 10 '13 18:04

Bernd Strehl


People also ask

Where do you put event handling code?

We can put the event handling code into one of the following places: Within class. Other class. Anonymous class.

Where are event listeners stored?

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.

What are event listeners and event handlers?

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.


1 Answers

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';
like image 133
Phill Sparks Avatar answered Oct 03 '22 02:10

Phill Sparks