Passa al contenuto principale
Versione: 2.x

Eventi backend

Spesso, un'estensione vorrà reagire ad alcuni eventi che si verificano da qualche parte in Flarum. Ad esempio, potremmo voler incrementare un contatore quando viene pubblicata una nuova discussione, inviare un'e-mail di benvenuto quando un utente accede per la prima volta o aggiungere tag a una discussione prima di salvarla nel database. These events are known as domain events, and are broadcasted across the framework through Laravel's event system.

Per un elenco completo degli eventi di backend, vedere la nostra API documentation. Le classi di eventi di dominio sono generalmente organizzate così Flarum\TYPE\Event.

È possibile utilizzare la CLI per generare automaticamente gli Event Listener:

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


return [
(new Extend\Event)
->listen(Deleted::class, function($event) {
// do something here
})
->listen(Deleted::class, PostDeletedListener::class)
];


class PostDeletedListener
{
protected $translator;

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

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

Ascolto di eventi​

Puoi allegare un ascoltatore a un evento utilizzando il file Event extender:

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
}
}
class PostDeletedListener
{
protected $translator;

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

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

Come mostrato sopra, è possibile utilizzare una classe listener invece di un callback. This allows you to inject dependencies into your listener class via constructor parameters. In questo esempio risolviamo un'istanza di un traduttore, ma possiamo iniettare tutto ciò che vogliamo/di cui abbiamo bisogno.

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']),
];
informazioni

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.

È inoltre possibile ascoltare più eventi in una sola volta tramite un event subscriber. Questo è utile per raggruppare le funzionalità comuni; per esempio, se si desidera aggiornare alcuni metadati sulle modifiche ai post:

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
}
}

Invio di eventi​

L'invio di eventi è molto semplice. L'invio di eventi è molto semplice. Per esempio:

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.
}),
];
suggerimento

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.

Eventi personalizzati​

In qualità di sviluppatore di estensioni, puoi definire i tuoi eventi per consentire a te stesso (o ad altre estensioni) di reagire agli eventi nella tua estensione. Gli eventi sono generalmente istanze di classi semplici (non è necessario estendere nulla). Quando si definisce un nuovo evento, in genere si desidera utilizzare proprietà pubbliche e forse alcuni metodi per la comodità degli utenti. Ad esempio, se diamo un'occhiata a Flarum\Post\Event\Deleted, è solo un contenitore di alcuni dati:

<?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;
}
}