Extensions (PHP) · Hook reference
Hook reference
Every place your extension can plug into ForumSpark, on one page. The other guides explain each kind with examples; this page is the list to keep open while you build. The tables below are read from ForumSpark itself, so they always match the version you run.
The kinds of hooks
| Kind | You call | Runs | Can change things | If it fails |
|---|---|---|---|---|
| Named events | listen, listenLater | After the action is saved, once per action | No, it reacts | Logged and counted, the action stays done |
| Record events | listen, listenLater for the after events | creating, updating, deleting during the save; created, updated, deleted after it | The before events can change the record or refuse the save | Logged and counted, the save goes ahead |
| System events | listen | While the request, mail or notification is handled | Yes, by what you return | Logged and counted, ForumSpark carries on as if you returned nothing |
| Page slots | A PageSlot class in contributes() | When the page shows that slot | Adds HTML in a fixed place | The slot stays empty, the page still shows |
| Template hooks | beforeTemplate, afterTemplate, modifyTemplate, templateData | Every time that template is shown | Adds to, changes or feeds any template | The template shows without your change |
| Page actions | beforeAction, afterAction | Around a page or form, chosen by route name | Answer the page yourself, or change or replace the response | The page runs as if you were not there |
| Record extensions | relation, scope | When code uses them | Adds relations and queries to core records | An error for the code that called it |
| Permissions | permission | Whenever ForumSpark checks that ability | Refuse any ability, allow any ability that is not a staff right | Ignored, the normal permissions decide |
| Form fields | formField | On the topic, reply, profile and sign-up forms | Adds a field that is checked and saved with the form | The form saves without your field |
A failure always counts towards the extension's error limit. Too many failures in a short time switch the extension off on that forum, with the reason shown in the admin panel, so a broken release never takes a forum down.
Which one to use
- Something happened and you want to react, like sending a welcome message: a named event, with
listenLaterwhen the work is slow. - You need to check or change data before it is stored: the record's
creatingorupdatingevent, and$this->refuse()to stop it with a message. - You want to show something in a common place, like under each post: a page slot. Slots survive theme changes.
- The place you need has no slot: a template hook. Prefer
beforeTemplateorafterTemplateon a small partial overmodifyTemplateon a whole page, because find-and-replace depends on the exact HTML. - You want to change how the forum handles requests, mail, notifications or post formatting: a system event.
- You want to stop or change one page, like closing the members list to guests:
beforeActionon its route name. - Your data belongs to a member or topic: keep it in your own table and add a
relation, so other code can use$member->yourname_pins. - Members ask for something extra when they post or sign up: a form field.
Named events
The same names as webhooks. Your listener gets the event object; the admin panel's Developer, Core events page lists what each one carries.
| Event | When |
|---|---|
topics/create | When a topic is created |
topics/update | When a topic is edited |
topics/delete | When a topic is deleted |
topics/lock | When a topic is locked |
topics/unlock | When a topic is unlocked |
topics/pin | When a topic is pinned |
topics/unpin | When a topic is unpinned |
topics/move | When a topic is moved to another forum |
topics/merge | When a topic is merged into another |
topics/approve | When a topic waiting for approval is approved |
replies/create | When a reply is posted |
replies/update | When a reply is edited |
replies/delete | When a reply is deleted |
replies/approve | When a reply waiting for approval is approved |
replies/move | When replies are moved to another topic |
reactions/add | When someone reacts |
reactions/remove | When a reaction is taken back |
users/create | When a member joins |
users/update | When a member is changed |
users/delete | When a member is deleted |
users/ban | When a member is banned |
users/login | When a member signs in |
groups/create | When a group is created |
groups/update | When a group is changed |
groups/delete | When a group is deleted |
reports/create | When something is reported |
credits/transaction | When credits change hands |
Record events
Add one of six moments to the record name: creating, updating, deleting, created, updated, deleted. Your listener gets the record itself. Records of apps a forum has not installed simply never fire.
| Record | Name | Class |
|---|---|---|
| Topic | topics/… | Topic |
| Reply | replies/… | Reply |
| Poll | polls/… | Poll |
| Poll vote | poll-votes/… | Vote |
| Reaction | reactions/… | ModelReaction |
| Attachment | attachments/… | Attachment |
| Tag | tags/… | Tag |
| Forum | forums/… | Forum |
| Label | labels/… | Label |
| Member | users/… | User |
| Group | groups/… | Group |
| Status update | status-updates/… | StatusUpdate |
| Status reply | status-replies/… | StatusUpdateReply |
| Conversation | conversations/… | Conversation |
| Private message | messages/… | Message |
| Shout | shouts/… | Shout |
| Report | reports/… | Report |
| Warning | warnings/… | Warning |
| Ban | bans/… | Ban |
| Member note | member-notes/… | MemberNote |
| Name change request | name-changes/… | NameChangeRequest |
| Event | events/… | Event |
| Event RSVP | event-attendees/… | EventAttendee |
| Arcade score | arcade-scores/… | ArcadeScore |
| Showcase entry | showcase-entries/… | ShowcaseEntry |
| Showcase review | showcase-reviews/… | ShowcaseEntryReview |
| Shop purchase | shop-purchases/… | ShopPurchase |
| Blog post | blog-posts/… | BlogPost |
| Gallery album | gallery-albums/… | MediaAlbum |
| Gallery item | gallery-items/… | MediaItem |
| Gallery comment | gallery-comments/… | MediaComment |
| Question | questions/… | AskQuestion |
| Marketplace product | marketplace-products/… | MarketplaceProduct |
| Marketplace order | marketplace-orders/… | MarketplaceOrder |
| Marketplace review | marketplace-reviews/… | MarketplaceReview |
| Club | clubs/… | Club |
The record events run for every save, also imports, moves and changes made by other extensions. Check what changed with $record->isDirty('title') or $record->wasChanged('title') before doing work.
System events
| Event | Your listener gets | Return |
|---|---|---|
request/starting | The request | A response to answer the request yourself, or nothing |
request/finished | The request and the response | A response to replace it, or nothing |
mail/sending | The email message and its data | false to stop the email; change the message in place to edit it |
notifications/sending | The member, the notification and the channel | false to stop it on that channel |
formatter/configure | The s9e TextFormatter configurator | Nothing; add BBCode or tags to the configurator |
users/logout | The member | Nothing |
users/verify | The member | Nothing |
users/password-reset | The member | Nothing |
System events run while the member waits and cannot use listenLater. The request events run on forum pages, the admin panel and the API. ForumSpark builds a separate formatter for each set of extensions that use formatter/configure, so your BBCode only exists on forums where your extension is on.
Page slots
A class that implements App\Modules\Contracts\PageSlot, listed in your extension's contributes(). Return the slot names from slots() and HTML from render($slot, $context); return null to show nothing.
| Slot | Where and what you get |
|---|---|
header | Under the forum header, on every page |
footer | Above the forum footer, on every page |
sidebar | In the sidebar, on pages that have one |
above_board | Above the forum list on the home page |
below_board | Below the forum list on the home page |
between_posts | Between two posts in a topic. Gets position |
reply_author | Under the author in each post. Gets member |
reply_author_stats | In the author details of each post. Gets member |
profile_header | In the header of a member profile. Gets member |
page_end | At the very end of every page |
forum_header | Above the topic list of a forum. Gets forum |
topic_header | Above the first post of a topic. Gets topic |
topic_end | Below the last post of a topic. Gets topic |
post_footer | Under the text of each post. Gets reply and member |
reply_composer | Below the quick reply box of a topic. Gets topic |
content_top | At the top of the content on every forum page. Gets route, the page name |
content_bottom | At the bottom of the content on every forum page. Gets route |
page_head_actions | Next to the buttons in the head of every page that has one. Gets route |
Template hooks
| Method | What it does |
|---|---|
beforeTemplate($view, fn (array $data) => …) | Adds your HTML before the template |
afterTemplate($view, fn (array $data) => …) | Adds your HTML after the template |
modifyTemplate($view, $find, $replace, regex: false) | Finds text or a pattern in the template's HTML and replaces it; $replace can be a function that gets the match and the data |
templateData($view, fn (array $data) => $data) | Changes the data before the template is shown; return the whole array |
Return a string, a view or nothing. Escape anything members wrote with e(). On a Livewire component's own template, before and after go just inside its outer element, because a component must keep one outer element. Template names look like topics.show or forum.topic-row; the admin panel's Developer, Templates page lists all 1,062 of them with a search. A modifyTemplate pattern that stops matching after a ForumSpark update simply changes nothing, so check your changes on each new version.
Page actions
$this->beforeAction('users.index', fn (Request $request) => auth()->guest() ? redirect()->route('login') : null);
$this->afterAction('topics.show', function (Request $request, Response $response) {
$response->headers->set('X-Pins', 'on');
});
Pick pages by route name, with * as a wildcard. A before action that returns a response answers the page instead of ForumSpark; return nothing to let the page run. An after action gets the response and can change it or return a new one. For a page, $response->original->getData() holds the data its template got. The route names are in php artisan route:list.
Relations and queries on core records
$this->relation('users', 'harbour_pins', fn (User $user) => $user->hasMany(Pin::class, 'user_id'));
$this->scope('topics', 'harbourPinned', fn (Builder $query) => $query->whereIn('id', Pin::query()->select('topic_id')));
$member->harbour_pins;
Topic::query()->harbourPinned()->latest()->get();
Use the record names from the table above. Start every name with your extension, so two extensions never pick the same one; a name that already exists on the record is refused when your extension starts. Keep your data in your own tables: extensions do not add columns to ForumSpark's tables. On a forum where your extension is off, the relation and the query do not exist.
Permissions
$this->permission('shout', fn (?User $member, string $ability, array $arguments) => $member?->harbour_pins()->exists() ? null : false);
$this->permission('harbour pin', fn (?User $member) => $member !== null && $member->num_posts >= 10);
Return false to refuse, true to allow, or null to leave it to the forum's own permissions. A refusal always wins. You can allow your own abilities and member abilities, but never staff rights like access admin, moderation, bans or warnings: those stay with the forum's groups. $arguments holds what the check was about, like the forum or the topic. For permissions per forum that admins set in the group screens, use forum permissions instead.
Form fields
$this->formField('topic', 'pin_note')
->label('Pin note')
->hint('Where should this topic sit on the map?')
->rules(['nullable', 'string', 'max:60'])
->value(fn (Topic $topic) => Pin::query()->where('topic_id', $topic->id)->value('note'))
->save(fn (Topic $topic, ?string $note) => Pin::query()->updateOrCreate(['topic_id' => $topic->id], ['note' => $note]));
| Form | Shown on | Saved with |
|---|---|---|
topic | New topic and edit topic | The topic |
reply | Quick reply, full reply and edit post | The post |
profile | Account, profile | The member |
register | Sign up | The new member |
Field types are text, textarea, number, url, checkbox and select (with ->type('select', ['a' => 'Label'])), or your own HTML with ->view(fn ($record, $value, $inputName) => ...). Your rules are checked before the form is handled, and a failed rule sends the member back with your message under the field. save runs only after the form succeeded, with the saved record. The field's input is named ext_{your extension}_{name}.
Everything your extension class can call
| Method | Use |
|---|---|
listen($event, $listener) | Run code for an event straight away |
listenLater($event, Job::class) | Queue a job for an after event |
refuse($message, $field = 'content') | Stop a save from a before event, with a message the member sees |
beforeTemplate, afterTemplate, modifyTemplate, templateData | Template hooks, above |
beforeAction($routes, $handler), afterAction($routes, $handler) | Page actions, above |
relation($record, $name, $define), scope($record, $name, $apply) | Relations and queries on core records |
permission($abilities, $decide) | Allow or refuse abilities |
formField($form, $name) | A field on a core form |
setting($key, $default) | Read one of your settings for this forum |
allows($member, $forum, $permission) | Check one of your forum permissions |
schema(), storage() | Your tables and your files |
cache() | Cached values kept to this forum and your extension: get, put, remember, increment, forget. The Cache facade is not allowed, because its keys are shared by every forum on the server. |
dispatch($job) | Queue a job on the extension queue for this forum |
charge($member, $title, $cents, $reference) | Ask a member to pay, see Uploads and payments |
http() | Call another website through the safe client |
One extension, every kind
A shortened version of Harbour Pins, the extension ForumSpark's own tests install from a zip to check that every hook works.
public function boot(): void
{
$this->listenLater('topics/create', NotifyMapFollowers::class);
$this->listen('topics/creating', function (Topic $topic) {
if (Str::length($topic->title) < 8) {
$this->refuse('Give your topic a title of at least 8 characters.', 'title');
}
});
$this->listen('formatter/configure', function ($configurator) {
$configurator->BBCodes->addCustom('[pin={NUMBER}]', '<a class="hm-pin" href="/map#{NUMBER}">Pin {NUMBER}</a>');
});
$this->afterTemplate('topics.partials.reply-content', fn (array $data) => view('harbour-member-map::pin-badge', ['member' => $data['reply']->author]));
$this->templateData('users.show', fn (array $data) => [...$data, 'pinCount' => Pin::query()->where('user_id', $data['user']->id)->count()]);
}