Saltar al contenido principal
Version: 2.x

Eventos del Backend

A menudo, una extensión querrá reaccionar a algunos eventos que ocurren en otra parte de Flarum. Por ejemplo, podríamos querer incrementar un contador cuando se publica una nueva discusión, enviar un email de bienvenida cuando un usuario se conecta por primera vez, o añadir etiquetas a una discusión antes de guardarla en la base de datos. These events are known as domain events, and are broadcasted across the framework through Laravel's event system.

Para obtener una lista completa de los eventos del backend, consulte nuestra documentación de la API. Las clases de eventos del dominio están organizadas por espacio de nombres, normalmente Flarum\TYPE\Event.

You can use the CLI to automatically generate event listeners:

use Flarum\Extend;
use Flarum\Post\Event\Deleted;
use Symfony\Contracts\Translation\TranslatorInterface;


return [
(new Extend\Event)
->listen(Deleted::class, function($event) {
// haz algo aquí
})
->listen(Deleted::class, PostDeletedListener::class)
];


class PostDeletedListener
{
protected $translator;

public function __construct(TranslatorInterface $translator)
{
$this->translator = $translator;
}

public function handle(Deleted $event)
{
// Su lógica aquí
}
}

Escuchar eventos​

Puedes adjuntar un oyente a un evento utilizando el [extensor] Event(start.md#extenders):

use Flarum\Post\Event\Deleted;
use Illuminate\Contracts\Events\Dispatcher;


class SomeClass
{
/**
* @var Dispatcher
*/
protected $events;

/**
* @param Dispatcher $events
*/
public function __construct(Dispatcher $events)
{
$this->events = $events;
}

public function someMethod()
{
// Lógica
$this->events->dispatch(
new Deleted($somePost, $someActor)
);
// Más lógica
}
}
class PostDeletedListener
{
protected $translator;

public function __construct(TranslatorInterface $translator)
{
$this->translator = $translator;
}

public function handle(Deleted $event)
{
// Your logic here
}
}

Como se muestra arriba, se puede utilizar una clase listener en lugar de un callback. This allows you to inject dependencies into your listener class via constructor parameters. En este ejemplo resolvemos una instancia de traductor, pero podemos inyectar cualquier cosa que queramos/necesitemos.

A listener can also name a class and the method to call on it, which is handy when one class handles several events. The class is resolved through the container in the same way, so it can take dependencies, and the method does not have to be static:

use Flarum\Extend;
use Flarum\Post\Event\Deleted;
use Flarum\Post\Event\Restored;

return [
(new Extend\Event)
->listen(Deleted::class, [PostCountListener::class, 'whenPostDeleted'])
->listen(Restored::class, [PostCountListener::class, 'whenPostRestored']),
];
info

Flarum 2.0.0 only accepts this form when the method is static: an instance method throws a TypeError when extend.php loads. From Flarum 2.0.1, either works.

You can also listen to multiple events at once via an event subscriber. This is useful for grouping common functionality; for instance, if you want to update some metadata on changes to posts:

use Flarum\Extend;
use Flarum\Post\Event\Deleted;
use Flarum\Post\Event\Saving;
use Symfony\Contracts\Translation\TranslatorInterface;


return [
(new Extend\Event)
->subscribe(PostEventSubscriber::class),
];
class PostEventSubscriber
{
protected $translator;

public function __construct(TranslatorInterface $translator)
{
$this->translator = $translator;
}

public function subscribe($events)
{
$events->listen(Deleted::class, [$this, 'handleDeleted']);
$events->listen(Saving::class, [$this, 'handleSaving']);
}

public function handleDeleted(Deleted $event)
{
// Your logic here
}

public function handleSaving(Saving $event)
{
// Your logic here
}
}

Dispatching de eventos​

Despachar eventos es muy sencillo. Despachar eventos es muy sencillo. Por ejemplo:

use Flarum\Post\Event\Deleted;
use Illuminate\Contracts\Events\Dispatcher;


class SomeClass
{
/**
* @var Dispatcher
*/
protected $events;

/**
* @param Dispatcher $events
*/
public function __construct(Dispatcher $events)
{
$this->events = $events;
}

public function someMethod()
{
// Logic
$this->events->dispatch(
new Deleted($somePost, $someActor)
);
// More Logic
}
}

Notable Core Events​

Most of Flarum's domain events are listed in the API documentation. A few lifecycle events are worth calling out specifically.

Flarum\Foundation\Event\ApplicationBooted​

Fired after the application has finished booting — all service providers have registered and booted, and all extension extenders have been applied — but before any HTTP request is handled. This is the earliest reliable point at which all bindings, extensions, and settings are fully available.

This is useful for one-time setup that must happen after the entire extension system is ready but before any request is processed:

use Flarum\Extend;
use Flarum\Foundation\Event\ApplicationBooted;

return [
(new Extend\Event())
->listen(ApplicationBooted::class, function () {
// Everything is booted. Safe to resolve any binding or read any setting.
}),
];
tip

This event fires on every request. If you are doing work that should only happen once (e.g. warming a cache), make sure to guard against repeated execution yourself.

Eventos personalizados​

Como desarrollador de extensiones puedes definir tus propios eventos para permitirte a ti mismo (o a otras extensiones) reaccionar a eventos en tu extensión. Los eventos son generalmente instancias de clases simples (no es necesario extender nada). Cuando definas un nuevo evento, normalmente querrás usar propiedades públicas, y quizás algunos métodos para la comodidad de los usuarios. Por ejemplo, si echamos un vistazo a Flarum\Post\Event\Deleted, es sólo una envoltura de algunos datos:

<?php

/*
* This file is part of Flarum.
*
* For detailed copyright and license information, please view the
* LICENSE file that was distributed with this source code.
*/

namespace Flarum\Post\Event;

use Flarum\Post\Post;
use Flarum\User\User;

class Deleted
{
/**
* @var Post
*/
public $post;

/**
* @var User
*/
public $actor;

/**
* @param Post $post
* @param User $user
*/
public function __construct(Post $post, User $actor = null)
{
$this->post = $post;
$this->actor = $actor;
}
}