Mostafa Talebi
Mostafa Talebi

Reputation: 9173

Laravel's Events listening and firing

I'm confused what is the difference between Laravel listening and firing.

Basically, I know their concept, but in practice I cannot figure them out.

Well, I want to echo a text when user visits pages/show. Here is my controller:

class Pages extedns Controller
{
 function show ()
 {
    echo "Welcome to our website.";
 }
}

Now here is my code block of events appended to global.php:

Event::listen("Pages.show", function(){
    echo "You have listened to one event!";
});

Now, how the above event should be triggered? How should I expect it to work? Because with this approach it does not work. But when I add the following line to this code, it works:

Event::fire("Pages.show");

Now, the problem is that the event is FIRED in every page and controller that I visit. It does not regard the Pages.show controller-method, it just triggers it. I appreciate if an expert clears my confusion.

Upvotes: 0

Views: 2752

Answers (1)

Joel Hernandez
Joel Hernandez

Reputation: 1897

Event listeners are just identified by strings , they do not relate to any other part of the application, to illustrate this in a simple way you could have something like this

Event::listen("logged",function($user){ 
  logEvent("{$user} logged in."); // Supposing that logEvent would write the message to a file.
});

And whenever a user authenticates, by that meaning password and username existed and matched, you would fire the event, it would look something like this

if($user->attemptLogin("myuser","password")){ //If the authentication function returns true
   Event::fire("logged",array($user->name)); //Fire the event and pass the username to be logged.
}

Note to all Laravel developers : I know that there is an uthentication method but I'm trying to keep things simple here.

So basically what you are doing is that you are giving a chunk of code a string identifier, and you can call that chunk on code by firing it's event.

Now, drifting away from my example, you attempted to listen to a function , as I said events identifiers are just strings which are not linked to anything else, so the solution is to simply call the event fire inside your function as :

Listener:

Event::listen("showedPage", function(){
    echo "You have listened to one event!";
});

Trigger:

class Pages extends Controller
{
 function show ()
 {
    echo "Welcome to our website.";
    Event::fire("showedPage");
 }
}

So every time the show function gets called , you will "trigger" or "fire" the chunk of code inside the listener.

Note that I changed the name of the event to denote that It has no direct relationship with the called function.

Upvotes: 1

Related Questions