Examples
class PluginServiceProvider extends ServiceProvider
{
public function register(ApplicationInterface $app): void
{
parent::register($app);
$this->singleton(HookManager::class, fn() =>
new HookManager($app->context())
);
}
}
class OrderService
{
public function __construct(
private HookManager $hooks,
private OrderRepository $repo
) {}
public function complete(Order $order): void
{
$this->repo->markComplete($order);
// Fire custom action for other parts to react
$this->hooks->doAction('order_completed', $order);
}
}
// Listener in another service
class NotificationService
{
public function register(HookManager $hooks): void
{
$hooks->action('order_completed', [$this, 'sendConfirmation']);
}
public function sendConfirmation(Order $order): void
{
// Send email...
}
}
class TemplateRenderer
{
public function __construct(private HookManager $hooks) {}
public function render(string $template, array $data): string
{
// Allow filtering data before render
$data = $this->hooks->applyFilter('template_data', $data, $template);
$output = $this->compile($template, $data);
// Allow filtering final output
return $this->hooks->applyFilter('template_output', $output, $template);
}
}
class AdminController
{
public function __construct(private HookManager $hooks) {}
public function init(): void
{
// WordPress hooks (no prefix)
$this->hooks->wpAction('admin_menu', [$this, 'addMenu']);
$this->hooks->wpAction('admin_init', [$this, 'registerSettings']);
$this->hooks->wpFilter('plugin_action_links', [$this, 'addLinks'], 10, 2);
}
}
// Flush rules only on first activation
$hooks->once('admin_init', function () {
if (get_option('my_plugin_needs_flush')) {
flush_rewrite_rules();
delete_option('my_plugin_needs_flush');
}
});