Events and Hooks

In LacePHP, events (also called hooks) let you decouple parts of your application. Instead of calling code directly, you fire an event at a certain point, and any number of listeners can react to it.

This is useful because:

  • Separation of concerns:

    Your core logic fires an event (user.registered), and email, logging or analytics code can live elsewhere.

  • Extensibility:

    Third-party plugins or future features can “listen” for events without modifying your original code.

  • Flexibility:

    You can add or remove listeners at runtime (for example, only in a particular environment).

Helper Functions

LacePHP provides two simple global functions:

// Dispatch (fire) an event with an optional payload
fire('user.registered', ['userId' => 42]);

// Register a listener for an event
on('user.registered', function(array $data) {
    // send welcome email, log analytics, etc.
});

Under the hood, both use the EyeletDispatcher class.

Basic Example

  1. Fire an event when a user registers:

    class RegistrationController
    {
        public function register()
        {
            // ... create the user ...
            $user = User::create($data);
    
            // Notify any listeners
            fire('user.registered', ['userId' => $user->id]);
    
            return kickback()->json(['status' => 'ok'], 201);
        }
    }
    
  2. Listen for the event elsewhere (for example in routes/system.php or a plugin boot file):

    on('user.registered', function(array $data) {
        // Send welcome email
        $user = User::find($data['userId']);
        Mailer::sendWelcome($user);
    });
    
  3. Wildcard listeners: catch all events if needed:

    on('*', function($payload) {
        // Log every event for audit
        error_log('Event fired: '.json_encode($payload));
    });
    

Advanced Usage

  • Multiple listeners on the same event run in the order they were registered.

  • Payload can be any value: object, array or simple scalar.

  • Error handling: individual listener exceptions are caught and logged, so one faulty listener won’t break the rest.

Best Practices

  • Name events clearly: use dot notation (e.g. order.created, payment.failed).

  • Keep listeners small: delegate heavy work to services or queued jobs.

  • Use wildcard sparingly: only for logging or debugging, not core logic.

  • Register listeners early: before you fire events (for example in routes/system.php).

Warning

  • If no listener is registered, fire() does nothing—this is safe and fast.

  • Avoid firing events inside tight loops unless you really need to.

  • Ensure listeners do not block the request for too long; offload heavy tasks to background jobs if possible.

By using events and hooks, you can write flexible, maintainable code, letting different parts of the application react to key moments without tight coupling.