Hooks, as the definition says, are events that call the action or filter functions, previously hooked to that events. In other words, Hook API allows you to trigger your application logic at specific times.
Injecting the Assely\Hook\HookFactory
provides access to the hook service. However, you can also use Hook
facade.
use Assely\Hook\HookFactory;
public function __construct(HookFactory $hook) {
$this->hook = $hook;
}
public function register() {
$this->hook->action('init', [$this, 'methodName'])->dispatch();
}
Call action
method for creating an action. Codex has a comprehensive actions reference list.
Hook::action($name, $callback);
Call filter
method for creating an action. The codex has a comprehensive filters reference list.
Hook::filter($name, $callback);
The Hook callback function can be defined in various ways. There are no recommendations, use the best in a given situation.
To reference a class method pass an array where the first element is a class instance and the second is a method name.
use Hook;
public function __constuct() {
Hook::action($name, [$this, 'methodName']);
}
public function methodName {
//
}
Sometimes you may need the easiest solution. Passing a Closure
simply does the job.
Hook::action($name, function() {
//
});
Another option is also a standard function.
function functionName() {
//
}
Hook::action($name, 'functionName');
You may need to specify the order in which the functions associated with a particular hook are executed. Use priority
option, lower number = higher priority.
Some hooks can pass more than one parameters to your callbacks. You can define it with numberOfArguments
option.
Hook::action($name, $callback, [
'piority' => 10,
'numberOfArguments' => 1
]);
Hook creation itself is not enough. After constructing, each hook must make some operation. It can be dispatched, detached or performed.
Delegate hook to perform at the appropriate time with dispatch
method.
Hook::action('name', $callback)->dispatch();
Hook::filter('name', $callback)->dispatch();
Call perform
method for executing hook callback.
Hook::action('name')->perform();
Hook::filter('name')->perform();
Calling detach
method will remove previously dispatched hook.
Hook::action('name', $callback)->detach();
Hook::filter('name', $callback)->detach();