PHP Classes

File: manuscript/6f.-Events.md

Recommend this page to a friend!
  Classes of Gjero Krsteski   PIMF   manuscript/6f.-Events.md   Download  
File: manuscript/6f.-Events.md
Role: Auxiliary data
Content type: text/markdown
Description: Auxiliary data
Class: PIMF
Framework for Web application development
Author: By
Last change: Update of manuscript/6f.-Events.md
Date: 2 months ago
Size: 2,350 bytes
 

Contents

Class file image Download

Events

Events can provide a great away to build de-coupled applications and allows you to tap into the core of your application without modifying its code.

Firing an event

To fire an event, just tell the Event class the name of the event you want to fire:

  $responses = Event::fire('user.updated');

Notice that we assigned the result of the fire method to a variable. This method will return an array containing the responses of all the event's listeners.

Firing an event and retrieving the first response

Sometimes you may want to fire an event, but just get the first response.

  $response = Event::first('user.updated');

Note: The first method will still fire all of the handlers listening to the event, but will only return the first response. The Event::until method will execute the event handlers until the first non-null response is returned.

Firing an event until the first non-null response

  $response = Event::until('user.updated');

Listening To Events

At the /app/YourAppName/events.php you can define your event listeners within the callbacks that should be executed. Just create the file /app/YourAppName/events.php and register an event listeners that will be called when an event fires:

  use Pimf\Event;

  Event::listen('user.deleted', function()
  {
      // I'm executed on the "user.deleted" event!
  });

The Closure we provided to the method will be executed each time the user.deleted event is fired.

PIMF Core Events

There are several events that are fired by the PIMF core.

The 404 Event

If a request enters your application but does not match any existing route, the 404 event will be raised. You can listen to it and send you a notification e-mail for example. You can define the event-listeners at you applications file /app/YourAppName/events.php


  use Pimf\Event;

  Event::listen('404', function()
  {
      // I'm executed on the "404" event!
      // send e-mail to admin...
  });

The 500 Event

All other critical problems or errors during your request will rise an 500 Internal Server Error, which can be listened and send you a notification e-mail for example.

  Event::listen('500', function()
  {
      // I'm executed on the "500" event!
      // send e-mail to admin...
  });