Skip to content

Commit 0878054

Browse files
committed
Add HookManager class
1 parent 70c6654 commit 0878054

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

src/HookManager.php

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
<?php
2+
namespace App;
3+
4+
class HookManager
5+
{
6+
protected array $hooks = [
7+
'before' => [],
8+
'after' => [],
9+
];
10+
11+
/**
12+
* Register a callback for a specific action and timing.
13+
*
14+
* @param string $action E.g. "create", "read", "update", "delete", or "*" for all
15+
* @param callable $callback
16+
* @param string $when "before" or "after"
17+
*/
18+
public function registerHook(string $action, callable $callback, string $when = 'before'): void
19+
{
20+
if (!in_array($when, ['before', 'after'])) {
21+
throw new \InvalidArgumentException("Invalid hook timing: $when");
22+
}
23+
$this->hooks[$when][$action][] = $callback;
24+
}
25+
26+
/**
27+
* Run hooks for a given action/timing.
28+
*
29+
* @param string $when "before" or "after"
30+
* @param string $action
31+
* @param array $context Data passed to hooks (by reference)
32+
*/
33+
public function runHooks(string $when, string $action, array &$context = []): void
34+
{
35+
foreach ([$action, '*'] as $key) {
36+
if (!empty($this->hooks[$when][$key])) {
37+
foreach ($this->hooks[$when][$key] as $callback) {
38+
$callback($context);
39+
}
40+
}
41+
}
42+
}
43+
}

0 commit comments

Comments
 (0)