Answer the question
In order to leave comments, you need to log in
Simple hook system in php?
Who can suggest a simple example of the implementation of hooks?
So that I can place hooks throughout the engine ($hook->register(name)), and then insert my function into this hook at the right time ($hook->run(name, function(){}).
Answer the question
In order to leave comments, you need to log in
Yes, there are not many options. The variable that stores the license type must be named licenseType.
class Hook {
protected $callbacks;
public function __construct($callbacks = []) {
$this->callbacks = [];
if (!isset($callbacks) || !is_array($callbacks) || sizeof($callbacks)) {
return;
}
foreach ($callbacks as $k => $v) {
if (!is_string($k) || !isset($v) || !is_callable($v)) {
continue;
}
$this->callbacks[$k] = $v;
}
}
public function add($key, $callback) {
if (!isset($key) || !isset($callback) || !is_string($key) || !is_callable($callback)) {
return;
}
$this->callbacks[$key] = $callback;
}
public function remove($key) {
if ($this->exists($key)) {
unset($this->callbacks[$key]);
}
}
public function exists($key) {
return isset($key) && array_key_exists($key, $this->callbacks);
}
public function run($key, ...$args) {
if ($this->exists($key)) {
$func = $this->callbacks[$key];
if (!isset($args) || !is_array($args)) {
$args = [];
}
if (isset($func)) {
$func(...$args);
}
}
}
}
$hook = new Hook();
$hook->add("my_hook", function ($args) {
// todo
});
$hook->run("my_hook");
$hook->run("my_hook", 1, "string", true);
As an option, you can scatter the following code:
And then, if necessary, connect the function.
Hook storage class:
Usage:
$hook = new h; // Creating a new object for Hook class
$hook->b('hook', function () {echo 'Hello, world!';}); // Creating the new hook
$hook->c('hook'); // Triggering all hooks that named 'hook'
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question