Start free trial

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

KindYou callRunsCan change thingsIf it fails
Named eventslisten, listenLaterAfter the action is saved, once per actionNo, it reactsLogged and counted, the action stays done
Record eventslisten, listenLater for the after eventscreating, updating, deleting during the save; created, updated, deleted after itThe before events can change the record or refuse the saveLogged and counted, the save goes ahead
System eventslistenWhile the request, mail or notification is handledYes, by what you returnLogged and counted, ForumSpark carries on as if you returned nothing
Page slotsA PageSlot class in contributes()When the page shows that slotAdds HTML in a fixed placeThe slot stays empty, the page still shows
Template hooksbeforeTemplate, afterTemplate, modifyTemplate, templateDataEvery time that template is shownAdds to, changes or feeds any templateThe template shows without your change
Page actionsbeforeAction, afterActionAround a page or form, chosen by route nameAnswer the page yourself, or change or replace the responseThe page runs as if you were not there
Record extensionsrelation, scopeWhen code uses themAdds relations and queries to core recordsAn error for the code that called it
PermissionspermissionWhenever ForumSpark checks that abilityRefuse any ability, allow any ability that is not a staff rightIgnored, the normal permissions decide
Form fieldsformFieldOn the topic, reply, profile and sign-up formsAdds a field that is checked and saved with the formThe 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 listenLater when the work is slow.
  • You need to check or change data before it is stored: the record's creating or updating event, 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 beforeTemplate or afterTemplate on a small partial over modifyTemplate on 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: beforeAction on 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.

EventWhen
topics/createWhen a topic is created
topics/updateWhen a topic is edited
topics/deleteWhen a topic is deleted
topics/lockWhen a topic is locked
topics/unlockWhen a topic is unlocked
topics/pinWhen a topic is pinned
topics/unpinWhen a topic is unpinned
topics/moveWhen a topic is moved to another forum
topics/mergeWhen a topic is merged into another
topics/approveWhen a topic waiting for approval is approved
replies/createWhen a reply is posted
replies/updateWhen a reply is edited
replies/deleteWhen a reply is deleted
replies/approveWhen a reply waiting for approval is approved
replies/moveWhen replies are moved to another topic
reactions/addWhen someone reacts
reactions/removeWhen a reaction is taken back
users/createWhen a member joins
users/updateWhen a member is changed
users/deleteWhen a member is deleted
users/banWhen a member is banned
users/loginWhen a member signs in
groups/createWhen a group is created
groups/updateWhen a group is changed
groups/deleteWhen a group is deleted
reports/createWhen something is reported
credits/transactionWhen 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.

RecordNameClass
Topictopics/…Topic
Replyreplies/…Reply
Pollpolls/…Poll
Poll votepoll-votes/…Vote
Reactionreactions/…ModelReaction
Attachmentattachments/…Attachment
Tagtags/…Tag
Forumforums/…Forum
Labellabels/…Label
Memberusers/…User
Groupgroups/…Group
Status updatestatus-updates/…StatusUpdate
Status replystatus-replies/…StatusUpdateReply
Conversationconversations/…Conversation
Private messagemessages/…Message
Shoutshouts/…Shout
Reportreports/…Report
Warningwarnings/…Warning
Banbans/…Ban
Member notemember-notes/…MemberNote
Name change requestname-changes/…NameChangeRequest
Eventevents/…Event
Event RSVPevent-attendees/…EventAttendee
Arcade scorearcade-scores/…ArcadeScore
Showcase entryshowcase-entries/…ShowcaseEntry
Showcase reviewshowcase-reviews/…ShowcaseEntryReview
Shop purchaseshop-purchases/…ShopPurchase
Blog postblog-posts/…BlogPost
Gallery albumgallery-albums/…MediaAlbum
Gallery itemgallery-items/…MediaItem
Gallery commentgallery-comments/…MediaComment
Questionquestions/…AskQuestion
Marketplace productmarketplace-products/…MarketplaceProduct
Marketplace ordermarketplace-orders/…MarketplaceOrder
Marketplace reviewmarketplace-reviews/…MarketplaceReview
Clubclubs/…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

EventYour listener getsReturn
request/startingThe requestA response to answer the request yourself, or nothing
request/finishedThe request and the responseA response to replace it, or nothing
mail/sendingThe email message and its datafalse to stop the email; change the message in place to edit it
notifications/sendingThe member, the notification and the channelfalse to stop it on that channel
formatter/configureThe s9e TextFormatter configuratorNothing; add BBCode or tags to the configurator
users/logoutThe memberNothing
users/verifyThe memberNothing
users/password-resetThe memberNothing

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.

SlotWhere and what you get
headerUnder the forum header, on every page
footerAbove the forum footer, on every page
sidebarIn the sidebar, on pages that have one
above_boardAbove the forum list on the home page
below_boardBelow the forum list on the home page
between_postsBetween two posts in a topic. Gets position
reply_authorUnder the author in each post. Gets member
reply_author_statsIn the author details of each post. Gets member
profile_headerIn the header of a member profile. Gets member
page_endAt the very end of every page
forum_headerAbove the topic list of a forum. Gets forum
topic_headerAbove the first post of a topic. Gets topic
topic_endBelow the last post of a topic. Gets topic
post_footerUnder the text of each post. Gets reply and member
reply_composerBelow the quick reply box of a topic. Gets topic
content_topAt the top of the content on every forum page. Gets route, the page name
content_bottomAt the bottom of the content on every forum page. Gets route
page_head_actionsNext to the buttons in the head of every page that has one. Gets route

Template hooks

MethodWhat 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]));
FormShown onSaved with
topicNew topic and edit topicThe topic
replyQuick reply, full reply and edit postThe post
profileAccount, profileThe member
registerSign upThe 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

MethodUse
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, templateDataTemplate 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()]);
}