Updating plugins with custom hooks for Kirby 3.4+

Since hook arguments in Kirby 3.4 “are now named and magically provided as requested” (release notes), this introduces a breaking change for plugins featuring custom hooks: when calling $kirby->trigger(), the function now expects an array of named values rather than an ordered series of variables.

This is fine when creating new plugins requiring 3.4 as minimum, but changing the call for the trigger() function in updates to existing plugins would break their functionality on any site not (yet) updated to 3.4.

I thought to share this function I added to a plugin class, in case anybody else needs it:

/**
 * Helper function to trigger custom hooks in both Kirby 3.3 and 3.4 syntax;
 * translates vars array into variables for <v3.4, hands on array for v3.4+
 */
protected static function triggerHook(string $hook, array $vars)
{
    if (version_compare(\Kirby\Cms\App::version(), '3.4.0-rc.1', '<') === true) {
        kirby()->trigger($hook, ...array_values($vars));
    } else {
        kirby()->trigger($hook, $vars);
    }
}

Improvements welcome! (Thank you @lukasbestle for feedback on an earlier draft.)

Updated: comparison with 3.4.0 yields false for 3.4.0-rc.x as version_compare considers pre-release version as smaller than the final release; now comparing with 3.4.0-rc.1 and it works

8 Likes

I just realized it could be worth pointing out how to call this function (as there has been some confusion in an other context):

static::triggerHook('myplugin.action:before', ['page' => $page, 'data' => $data]);

So, the array in the function call has to be an associative array, as that’s what the new 3.4 syntax of ->trigger() expects.