M
M
maragon2017-07-25 14:54:17
Programming
maragon, 2017-07-25 14:54:17

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

5 answer(s)
V
Vitaly, 2019-02-17
@Jun06Man

Yes, there are not many options. The variable that stores the license type must be named licenseType.

I
ideological, 2019-02-22
@ideological

Write in Russian!

Y
Yuri Esin, 2017-07-25
@Exomode

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);

Something like this?

P
Pavel Kornilov, 2017-07-25
@KorniloFF

As an option, you can scatter the following code:
And then, if necessary, connect the function.

M
Matvey Pravosudov, 2017-07-25
@oxyberg

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 question

Ask a Question

731 491 924 answers to any question