I was impressed when I found out WordPress hooks such as Actions and Filters, where you can modify or change your whole CMS functionality just from one custom function and its hook. I'm looking for the method or architecture pattern or even code example, which will explain how does it work. What do you have to write to your custom class (for example) to allow you to change some core features? No matter CMS or programming language. It could be WordPress or custom JS/PHP CMS.
This can be done in many ways, but the basic concept is pretty simple. For this I’ll show you what WordPress does at a high level using these two functions:
apply_filters($name, $value, …$context)
{
global $filters;
foreach($filters[$name] ?? [] as $callback) {
$value = $callback($value, …$context);
}
return $value;
}
add_filter($name, $callback)
{
global $filters;
if(!isset($filters[$name])){
$filters[$name] = [];
}
$filters[$name][] = $callback;
}
The add_filter function is where programmers register their interest in changing something. The $name parameter is defined by WordPress and is unique to the location it is used in the code (or unique enough as long as multiple callers all do the same thing with the data). The $callback parameter is custom code to do something with the data, and return something. Everything in here is stored in a global array.
The apply_filters function is where WordPress code loops over the global array for a specific named key which returns a sub array where each element is a callback. It then calls each callback with the specific $value of interest, along with any optional $context that someone might need.
I’m missing a bunch of sanity checking in here, but that’s the gist. In WordPress’s case, there’s actually a dedicated object for filters that gets stored in the global array, and there’s priorities so programmers can hint at the order that their $callback gets registered at.
The usage is very simple in core code then:
// Normal code here
$data = get_data();
// See if anyone wants to change it
$data = apply_filters('after_get_data', $data);
// Back to normal code
Actions are similar to filters, and in WordPress’s case, they share the same core logic. The only major difference is that actions don’t return anything, but otherwise share the same pattern of a common $name along with some optional arguments.
Another way that WordPress allows extensions is through pluggable code. Basically, there’s a file that’s loaded really late with a bunch of functions wrapped in if(!function_exists('…')){}. This allows other programmers to create these functions and WordPress will use the programmers version instead of core’s.