Hooking into Application Events

Hooking into Concrete CMS's events is simple.

Application-Level

If you're writing custom code and simply need it to run for the current website, and have no interest in packaging it up for re-use elsewhere, add it to the application/bootstrap/app.php file.

In a Package

If you're hooking into events within a Package, you'll want to add this code to the package's on_start() method, in its controller.php file. This will ensure that the event is hooked into early in Concrete's bootstrapping process, as well as only hooked into when the package itself is actively installed.

Import the Events Class

If you're adding code within a package controller, make sure to import the Events class, which is an alias to Concrete\Core\Support\Facade\Events.

use Concrete\Core\Support\Facade\Events;

If you're adding this code at the application level, the Events class is already available – a "use" statement isn't necessary.

Code

Let's add some logging code that runs every time a user is added.

Events::addListener('on_user_add', function($event) {
    $user = $event->getUserInfoObject();
    \Log::info(sprintf('Added user %s', $user->getUserName()));
});

That's it! Simply pass an event to the Events::addListener method, and closure as the second parameter. Within the closure do whatever you need, including passing it to a separate class.

When working with the addListener method, the closure will usually get a single argument – an Event object. The type of event object is defined by the type of event you're working with (and there's no strict rule about this, so sometimes it might be easiest to simply start your addListener callbacks with var_dump($event) or a debugger breakpoint in order to determine which event object you're working with. The on_user_add method works with the Concrete\Core\User\Event\UserInfoWithPassword event object.