A lightweight, WordPress-style hooks system for PHP. Add actions and filters with priority support to create extensible, event-driven applications.
- ✅ WordPress-inspired API (
addAction,addFilter,doAction,applyFilter) - ✅ Priority-based execution order
- ✅ Multiple callbacks per hook
- ✅ Multiple hook names in a single call
- ✅ Optimized sorting (sorted once, cached until modified)
- ✅ Type-safe with strict types
- ✅ Zero dependencies
composer require kristos80/hookuse Kristos80\Hook\Hook;
$hook = new Hook();
// Add a filter
$hook->addFilter('format_title', function(string $title) {
return strtoupper($title);
});
// Apply the filter
$result = $hook->applyFilter('format_title', 'hello world');
echo $result; // HELLO WORLDLower priority numbers run first (default is 10):
$hook->addFilter('modify_value', function(int $value) {
return $value * 2;
}, 10);
$hook->addFilter('modify_value', function(int $value) {
return $value + 5;
}, 5); // Runs first
$result = $hook->applyFilter('modify_value', 10);
echo $result; // 30 (first: 10 + 5 = 15, then: 15 * 2 = 30)Actions are filters that don't return values:
$hook->addAction('user_login', function() {
error_log('User logged in');
});
$hook->doAction('user_login');$hook->addFilter('format_name', function(string $name, string $prefix) {
return $prefix . ' ' . $name;
}, 10, 2); // Accept 2 arguments
$result = $hook->applyFilter('format_name', 'John', 'Mr.');
echo $result; // Mr. JohnRegister the same callback to multiple hooks at once:
$hook->addAction(['init', 'startup', 'boot'], function() {
// Initialization logic
});
$hook->doAction('init'); // Executes callback
$hook->doAction('startup'); // Executes callback
$hook->doAction('boot'); // Executes callbackaddFilter(string|array $hookNames, callable $callback, int $priority = 10, int $acceptedArgs = 0): void
Add a filter callback to one or more hooks.
$hookNames- Hook name(s) to attach to$callback- Callable to execute$priority- Execution priority (lower = earlier, default: 10)$acceptedArgs- Number of arguments the callback accepts (default: 0)
addAction(string|array $hookNames, callable $callback, int $priority = 10, int $acceptedArgs = 0): void
Alias for addFilter(). Use for hooks that don't return values.
Execute all callbacks registered to a filter hook.
$hookName- Hook name to execute...$arg- Arguments to pass to callbacks- Returns the filtered value
Execute all callbacks registered to an action hook.
$hookName- Hook name to execute...$arg- Arguments to pass to callbacks
./vendor/bin/pestMIT
Christos Athanasiadis - chris.k.athanasiadis@gmail.com