gjerokrsteski/pimf-framework

View on GitHub
manuscript/6f.-Events.md

Summary

Maintainability
Test Coverage
# 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:

```php
  $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.

```php
  $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

```php
  $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:

```php
  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**

```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.


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