Hook

Introduction

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.

Creating Hooks

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

Action Hooks

Call action method for creating an action. Codex has a comprehensive actions reference list.

Hook::action($name, $callback);

Filter Hooks

Call filter method for creating an action. The codex has a comprehensive filters reference list.

Hook::filter($name, $callback);

Callback Functions

The Hook callback function can be defined in various ways. There are no recommendations, use the best in a given situation.

Method name

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 {
    //
}

Closure

Sometimes you may need the easiest solution. Passing a Closure simply does the job.

Hook::action($name, function() {
    //
});

Function name

Another option is also a standard function.

function functionName() {
    //
}

Hook::action($name, 'functionName');

Piority and number of arguments

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

Basics of Hooking

Hook creation itself is not enough. After constructing, each hook must make some operation. It can be dispatched, detached or performed.

Dispaching Hooks

Delegate hook to perform at the appropriate time with dispatch method.

Hook::action('name', $callback)->dispatch();

Hook::filter('name', $callback)->dispatch();

Performing Hooks

Call perform method for executing hook callback.

Hook::action('name')->perform();

Hook::filter('name')->perform();

Detaching Hooks

Calling detach method will remove previously dispatched hook.

Hook::action('name', $callback)->detach();

Hook::filter('name', $callback)->detach();